1. What is SQL injection
SQL Injection is the behavior of a user exploiting some systems that do not adequately check the input data for malicious damage.
For example, the login user name takes ' or 1=1 or username= ', the background data query becomes
sql = SELECT * from users where username= ' or 1=1 or username= ' and password= ' "+password+" ' because SQL has a higher precedence than or, so the entire query statement, etc. Price at:
sql = SELECT * from users where true, which results in random login
2. Preventing SQL injection Preperedstatement is a child of Statement , and its instance object can be obtained by calling the connection.preparedstatement () method, relative to Statement objects:preperedstatement can avoid problems with SQL injection. Statement causes the database to compile SQLfrequently, which may cause the database buffer overflow preparedstatement to SQL To improve the efficiency of database execution. and preperedstatement for parameters in SQL , allowing for substitution in the form of placeholders, simplifying the writing of SQL statements.
1 Public voidAdd (user user) {2Connection conn =NULL;3PreparedStatement st =NULL;4ResultSet rs =NULL;5 Try{6conn =jdbcutils.getconnection (); 7 String sql = "INSERT into users (Id,username,password,email,birthday,nickname) VALUES (?,?,?,?,?,?)"; /Use placeholder 8th = conn.preparestatement (SQL);9St.setstring (1, User.getid ());TenSt.setstring (2, User.getusername ()); OneSt.setstring (3, User.getpassword ()); ASt.setstring (4, User.getemail ()); -St.setdate (5,Newjava.sql.Date (User.getbirthday (). GetTime ())); -St.setstring (6, User.getnickname ()); the intnum =st.executeupdate (); - if(num<1){ - Throw NewRuntimeException ("User does not exist"); - } +}Catch(Exception e) { - Throw Newdaoexception (e); +}finally{ A Jdbcutils.release (Conn, St, RS); at } - - -}
Using PreparedStatement to prevent SQL injection