/**
* 什么时候用PreparedStatement替代Statement
* 反复执行一条结构相似的语句
* 可以用占位符实现(?)
*
*/
package ConnectMySql;
import java.sql.*;
public class ConnMySQL03PrepareStatement {
private String diver;
private String url;
private String username;
private String password;
Connection connection;
Statement statement;
PreparedStatement preparedStatement;
public ConnMySQL03PrepareStatement(){
this.diver="com.mysql.cj.jdbc.Driver";
this.url="jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=GMT";
this.username = "root";
this.password="123456";
}
public ConnMySQL03PrepareStatement(String diver, String url, String username, String password) {
this.diver = diver;
this.url = url;
this.username = username;
this.password = password;
}
public void insertByStatement( )throws Exception {
try {
long start =System.currentTimeMillis();
statement =connection.createStatement();/*创建一个基本对象*/
for (int i = 0; i < 100; i++) {
statement.executeUpdate("insert into for_compare_jdbc values (null ,'姓名"+i+"',1)");
}
System.out.println("使用Statement费时:"+(System.currentTimeMillis()-start));
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (statement != null) {
statement.close();
}
}
}
public void insertUsePrepareStatement()throws Exception{
try {
long start=System.currentTimeMillis();
preparedStatement =connection.prepareStatement("insert into for_compare_jdbc values (null ,?,1 )");
for (int i = 0; i < 100; i++) {
preparedStatement.setString(1,"姓名"+i);
preparedStatement.executeUpdate();
}
System.out.println("使用PreparedStatement 费时:"+(System.currentTimeMillis()-start));
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (preparedStatement != null) {
preparedStatement.close();
}
}
}
public void getConnect()throws Exception{
if(connection==null) {
Class.forName(diver);
connection=DriverManager.getConnection(url,username,password);
}
}
public void closeClean()throws Exception{
if (connection != null) {
connection.close();
}
}
}
运行时间
使用PreparedStatement 费时:7496
使用Statement费时:39688
如果换了顺序
使用Statement费时:7657
使用PreparedStatement 费时:9925
这是为什么呢,诡异呀