Let's look at the following sentence with a placeholder
String sql = "SELECT * from Administrator where adminname=?";
PSM = con.preparestatement (sql);
String s_name = "Zhangsan ' or ' 1 ' = ' 1";
Psm.setstring (1, s_name);
Assuming that the user name is not zhangsan in the database table,
Run the SQL statement with Plsql, you can find out all the user names, but in Java did not find any data, this is why?
First of all, the source of setString () only the method name, and there is no procedural processing,
Then the answer must appear in the Java to the database process, that is, MySQL and Oracle driver package, in the MySQL driver package, PreparedStatement inherits and implements the SetString method in the JDK,
The reason is that the database vendors to help you solve the problem, the following look at the specific implementation of this method:
Public voidSetString (intParameterindex, String x)throwsSQLException {//if the passed string is null and then set this column to null if(x = =NULL) {setnull (Parameterindex, Types.char); } Else{stringbuffer buf=NewStringBuffer ((int) (X.length () * 1.1)); Buf.append (‘\‘‘); intStringlength =x.length (); // //Note:buf.append (char) is _faster_ than//appending in blocks, because the block//append requires a system.arraycopy () ....//Go figure ...// for(inti = 0; i < stringlength; ++i) {Charc =X.charat (i); Switch(c) { Case0:/*must is escaped for ' MySQL '*/Buf.append (‘\\‘); Buf.append (' 0 '); Break; Case' \ n ':/*must is escaped for logs*/Buf.append (‘\\‘); Buf.append (N); Break; Case' \ r ': Buf.append (‘\\‘); Buf.append (' R '); Break; Case‘\\‘: Buf.append (‘\\‘); Buf.append (‘\\‘); Break; Case‘\‘‘: Buf.append (‘\\‘); Buf.append (‘\‘‘); Break; Case‘"‘:/*Better safe than sorry*/ if( This. Usingansimode) {Buf.append (‘\\‘); } buf.append (‘"‘); Break; Case' \032 ':/*This gives problems on Win32*/Buf.append (‘\\‘); Buf.append (Z); Break; default: Buf.append (c); }} buf.append (‘\‘‘); String parameterasstring=buf.tostring (); byte[] Parameterasbytes =NULL; if(! This. Isloaddataquery) {Parameterasbytes=stringutils.getbytes (parameterasstring, This. Charconverter, This. charencoding, This. Connection. getservercharacterencoding (), This. Connection. Parserknowsunicode ()); } Else { //Send with platform character encodingParameterasbytes =parameterasstring.getbytes (); } setinternal (Parameterindex, parameterasbytes); } }
So the escaped SQL is ' zhangsan\ ' or \ ' 1\ ' =\ ' 1 '; this time is not to be found.
Why are placeholders preventing SQL injection?