java.sql.PreparedStatement(SQL preprocessing)
Prevent SQL injection
As long as your sql parameters are provided by users, you need to use sql preprocessing
When setting parameters, you need to select the corresponding data type to set, otherwise there will be problems when processing the type
One of the advantages of setObject is that you can judge any type, identify your type and set it
sql anti injection code example:
import java.sql.*; import java.util.Arrays; import java.util.Scanner; public class T4 { public static void main(String[] args) throws SQLException { java.util.Scanner input = new Scanner(System.in); System.out.print("Please enter your login account:"); String Account = input.next(); System.out.print("Please enter your login password:"); String Password = input.next(); Connection connection = T3.getT3().getconnection(); Statement statement = connection.createStatement(); PreparedStatement pst = connection.prepareCall("select *from zangu where account=? AND password=?"); // Use the prepareCall class in the Connection object to receive sql statements and create the PreparedStatement interface object pst.setString(1, Account); //Call the setString method through the PreparedStatement class. What you need to input is the number one. Here we choose the String type, so the input is the String type //Of course, you can also choose int method in PreparedStatement pst.setString(2, Password); //The principle here is the same as that of calling setString method through PreparedStatement class. What you need to input is the number and type ResultSet resultSet = pst.executeQuery(); //Create a query with PreparedStatement //Here, the resultSet Recordset object class is created to accept the resultSet recordset of the query number statement.executeUpdate("create table zangu(zid int(11)primary key,account varchar(100)," + "password varchar(100))engine=innodb charset=utf8");//Create the table only once. Note that if you call this class again, an error will be reported statement.executeUpdate("insert into zangu values(1,'Zhang San','123456') "); ResultSet resultSet = statement.executeQuery("select *from zangu where account='"+ Account+"'and password='"+Password+"'");//In this way, there is sql injection problem 'or' '=' in sub validation, which will essentially rewrite the code sql anti injection batch processing to add PreparedStatement/*Note that this is a batch class*/ pst = connection.prepareStatement("INSERT into zangu values(?,?,?)"); pst.setObject(1, 2); pst.setObject(2, "Li Si"); pst.setString(3, "0"); pst.addBatch();//This method is called after each round of code execution pst.setObject(1, 3); pst.setObject(2, "Zhao Liu"); pst.setObject(3, "125"); pst.addBatch(); pst.setObject(1, 4); pst.setObject(2, "Laughing and laughing"); pst.setObject(3, "315"); pst.addBatch(); int a[] = pst.executeBatch();//Transfer batch to array System.out.println(Arrays.toString(a));//Print record } }