1. The inconvenient use of statement 2.
The problem of sql injection
* The keyword or and that comes with the system is used in the SQL statement to make the where condition judgment invalid
*
prepareStatement:
* 1. The sql statement does not need to spell strings
* 2. Prevent sql injection problems
1 public class CURDTest { 2 public static void main(String[] args) throws Exception { 3 // insertTest(); 4 // deleteTest(); 5 // updateTest(); 6 // selectTest(); 7 deleteTest2( ); 8 } 9 // Deletion method 2: get the precompiled statement object 10 // PreparedStatement 11 // Prevent sql injection problem 12 private static void deleteTest2() throws Exception { 13 // Register the driver 14 Class.forName("com.mysql.jdbc.Driver" ); 15 // Create a connection 16 Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/day01", "root", "root" ); 17 // Create Statement object 18 String sql = "delete from stu where id =? or name =?" ; 19 PreparedStatement pst = conn.prepareStatement(sql); 20 pst.setInt(1,7); // (The content id=6 of the 1st ?,?) 21 pst.setString(2, "Baby"); // (The content of the 2nd ?,? name = "Baby" ) 22 // 23 int i = pst.executeUpdate(); 24 if (i!=0 ) { 25 System.out.println("Delete successful" ); 26 } 27 pst.close(); 28 conn.close(); 29 } 30 31 // Delete 32 private static void deleteTest() throws Exception { 33 // TODO Auto-generated method stub 34 // Register the driver 35 Class.forName("com.mysql.jdbc.Driver" ); 36 // Create a connection 37 Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/day01", "root", "root" ); 38 // Create Statement object 39 Statement st = conn.createStatement(); 40 // sql injection Question 41 // The keyword or and that comes with the system is used in the SQL statement, which makes the where condition judgment invalid 42 // String sql = "delete from stu where id= 1 or 1=1"; // SQL injection problem , will delete the contents of the entire table 43 String sql = "delete from stu where id= 1" ; 44 int i = st.executeUpdate(sql); 45 if (i!=0 ) { 46 System.out.println("Delete successful" ); 47 } 48 st.close(); 49 conn.close(); 50 } 51 }