In the previous article, I learned how to configure mysql through java connections. In this article, I learned how to process SQL pre-processing statements (PreparedStatement). The first is an example of SQL pre-processing:
main(String[] args) Connection connection = Statement statement = ResultSet resultSet = String sqlurl = "jdbc:mysql://172.20.23.75:3306/testdb" String sqluser = "root" String sqlpassword = "123456" starttime= connection = PreparedStatement prestatement = connection.prepareStatement("INSERT INTO Testing(Id) VALUES(?)" prestatement.setInt(1, 1001 } } (resultSet != (statement != (connection != } System.out.println(System.currentTimeMillis()- }
First, let's talk about the benefits of prepared statement.
2. Because the placeholder is used to replace the specific parameters in the SQL statement at the beginning of the prepared statement, the parameterization of the SQL statement can be used to avoid the occurrence of SQL inject.
After the prepared statement is created, we can set the parameters.
prestatement.setInt(1, 1001);
Then execute the SQL statement
prestatement.executeUpdate();
Ps: executeupdate is used here because we do not need to obtain the returned results, so executeUpdate can be used when we Create, delete, insert, and update.
So how much can the prepared statement improve the running time? We can use two examples to compare them:
1. Honest and practical executequery
Connection = (I = 1; I <= 1000; I ++ = "insert into Testing (Id) VALUES (" + 2 * I + ")" // 5511 MS
2. Use prepared statement
Connection = connection. prepareStatement ("insert into Testing (Id) VALUES (?) "(I = 1; I <1000; I ++ 1, I * 2 // time consumed: 4123 ms
Therefore, prepared statement can improve the running efficiency.