1, PreparedStatement is the statement subinterface, you can pass in the SQL statement with the placeholder, and provide the appropriate method to replace the placeholder (setxxx (int index, Object value) index starting from 1),
The SQL statement is then executed through the executeupdate or ExecuteQuery () method.
2. Update operation
Public intUpdate (String sql, Object ... args) {intRowNum = 0; Connection Conn=NULL; PreparedStatement PS=NULL; Try{conn=getconnection (); PS=conn.preparestatement (SQL); for(inti = 0; i < args.length; i++) {Ps.setobject (i+ 1, Args[i]); } rowNum=ps.executeupdate (); returnRowNum; }Catch(Exception e) {e.printstacktrace (); }finally{ if(PS! =NULL){ Try{ps.close (); } Catch(SQLException e) {e.printstacktrace (); } } if(Conn! =NULL){ Try{conn.close (); } Catch(SQLException e) {e.printstacktrace (); } } } returnRowNum;}
3. Query operation
Public Static voidquery () {Connection conn=NULL; PreparedStatement PS=NULL; ResultSet RS=NULL; StringBuffer SB=NewStringBuffer ("Select name, email, salary from EMP1"); Sb.append ("Where id =?"); Try{conn=getconnection (); PS=conn.preparestatement (sb.tostring ()); Ps.setint (1, 1234); RS= Ps.executequery ();
if(Rs.next ()) {String name= rs.getstring (1); String Email= Rs.getstring (2); DoubleSalary = rs.getdouble (3); SYSTEM.OUT.PRINTLN (Name+ ":" + email + ":" +salary); } }Catch(Exception e) {e.printstacktrace (); }finally{ if(rs! =NULL){ Try{rs.close (); } Catch(SQLException e) {e.printstacktrace (); } } if(PS! =NULL){ Try{ps.close (); } Catch(SQLException e) {e.printstacktrace (); } } if(Conn! =NULL){ Try{conn.close (); } Catch(SQLException e) {e.printstacktrace (); } } }}
4. SQL injection attack: The use of the system's SQL engine to complete malicious behavior is done by using some systems that do not adequately check the data entered by the user, but inject illegal SQL statements or commands into the user input.
5, using PreparedStatement can effectively avoid SQL injection. and statement cannot prohibit SQL injection;
6. Using PreparedStatement can improve the readability and maintainability of the code, and it can maximize performance.
Jdbc--preparedstatement use