Understand SQL injection from scratch, what is SQL injection? SQL injection means that I am the only one who can operate the database. I just let you enter the content and leave, but you enter the command, thereby operating the database without my knowledge
Look at the following case scenario, this is the login scenario under normal circumstances:
And when we use the username':-, we can log in successfully even if we enter the password casually↓
At this time, comparing the two SQLs, we can find that in fact, the user ended the internal SQL early by writing the SQL symbols in the user name, and commented out the search conditions in the second half of the sentence to avoid the problem. Password login effect.
sql injection is that I am the only one who can operate the database. I just let you enter the content and leave, but you enter the command, thereby operating the database without my knowledge
The reason why the above sql is used is dynamic splicing, so the way the sql is passed in may Change the semantics of sql.
Dynamic splicing is the mixed use of java variables and sql statements in java: select * from user where userName='" userName ''' and password = '" password"'
So use preparedStatement's parameterized sql. By first determining the semantics and then passing in the parameters, the semantics of the sql will not be changed due to the passed in parameters. (Pass in parameters through setInt, setString, setBoolean)
//建立数据连接 conn=ds.getConnection(); //1.设置prepareStatement带占位符的sql语句 PreparedStatement ptmt = conn.prepareStatement("select * from user where userName = ? and password = ?"); ptmt.setString(1, "张三"); //2.设置参数 ptmt.setString(2, "123456"); rs=ptmt.executeQuery(); while(rs.next()){ System.out.println("登陆成功"); return; } System.out.println("登陆失败");
Parameterized features:
1. Set the preparedStatement sql statement with placeholder
The way statement executes sql statement:
stmt=conn.createStatement(); rs=stmt.executeQuery("select userName from user");
2. Set parameters
PerparedStatement inherits from Statement, and the features used here mainly make it parameterized sql.
Redirect: https://blog.csdn.net/qq_30258957/article/details/78145885
Added: 1. PreparedStatement extends Statement;# which are all used to execute SQL.
##2.Statement is suitable for executing static (unconditional) SQL. PreparedStatement is suitable for executing dynamic (conditional) SQL;3.PreparedStatement can avoid injection attacks; Related articles:A PHP anti-SQL injection that I think is very safe needs to be cracked
In-depth understanding of SQL injection and preventive measures
Related videos:Defense against sql injection-PHP practical mall development video tutorial
The above is the detailed content of What is SQL injection? Take you to understand SQL injection from scratch. For more information, please follow other related articles on the PHP Chinese website!