SQL Injection, PreparedStatement, and Statement
* If an SQL Statement contains special characters or keywords (for example, 'or 1 or'), an unexpected result (exception or incorrect query result) is returned ), it can be solved by PreparedStatement.
* Advantages of PreperedStatement over Statement:
1. There is no SQL Injection problem.
2. Statement: the database frequently compiles SQL statements, which may cause database Buffer Overflow.
3. The database and driver can optimize the PreperedStatement (only when the associated database connection is not closed ).
SQLInject. java
Package cn. itcast. jdbc;
Import java. SQL. Connection;
Import java. SQL. PreparedStatement;
Import java. SQL. ResultSet;
Import java. SQL. SQLException;
Import java. SQL. Statement;
Public class SQLInject {
/**
* @ Param args
* @ Throws SQLException
*/
Public static void main (String [] args) throws SQLException {
// Read1 ("admin ");
Read1 ("'or 1 or '");
}
Static void read1 (String userid) throws SQLException {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
Try {
// 2. Establish a connection
Conn = JdbcUtils. getConnection ();
// Conn = JdbcUtilsSing. getInstance (). getConnection ();
// 3. Create a statement
String SQL = "select id, userid, uname, loginip from dede_admin where userid = '"
+ Userid + "'";
// This method can also be checked, but it is not rigorous. For example, if you execute read ("'or 1 or'"), all the results will be displayed.
// Or is the keyword of mysql, and 1 is true. Therefore, it is insecure to use the String concatenation method, because the parameters are transmitted by others,
// In this way, our system has security risks. For example, when logging on, you can write a password
// This problem is caused by single quotes. Replacing single quotes is a processing method, but sometimes single quotes are reserved words,
// Sometimes double quotation marks are reserved words, and sometimes reverse quotation marks are reserved words. In this way, filtering is endless,
// Even if you can ensure that the database can run normally now, you cannot ensure that the database can run normally in the future,
// Who knows the keywords most clearly? The database manufacturer should be the clearest, but in our code? Who knows best?
// The driver is the clearest, because the driver is produced by the database manufacturer, so the driver must be clear.
// Our solution is to leave the database driver alone to do this without filtering.
System. out. println ("SQL =" + SQL );
St = conn. createStatement ();
// 4. Execute the statement
Rs = st.exe cuteQuery (SQL );
// 5. processing result
While (rs. next ()){
System. out. println (rs. getObject ("id") + "\ t"
+ Rs. getObject ("userid") + "\ t" + rs. getObject ("uname ")
+ "\ T" + rs. getObject ("loginip "));
}
} Finally {
JdbcUtils. free (rs, st, conn );
}
}
}