1、statement
@org.junit.Test
public void teststatement() throws Exception {
long start = System.currentTimeMillis();
//创建连接
String driverClass = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/mysql_jdbc";
String username = "root";
String password = "root";
Class.forName(driverClass);
Connection con = DriverManager.getConnection(url, username, password);
//关闭自动提交
con.setAutoCommit(false);
//创建语句
Statement st = con.createStatement();
for(int i = 1; i < 10000 ; i++){
String sql = "insert into student values( " + i + " , " + "'tom "+ i + "', " + (i % 100) + ")";
st.execute(sql);
}
//提交
con.commit();
st.close();
con.close();
long time = System.currentTimeMillis() - start;
System.out.println(time);//885
}
2、prepared statement
@org.junit.Test
public void testpreparedstatement() throws Exception {
long start = System.currentTimeMillis();
//创建连接
String driverClass = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/mysql_jdbc";
String username = "root";
String password = "root";
Class.forName(driverClass);
Connection con = DriverManager.getConnection(url, username, password);
//关闭自动提交
con.setAutoCommit(false);
//创建预处理语句
String sql = "insert into student values( ?,?,?)";
PreparedStatement ps = con.prepareStatement(sql);
for(int i = 1; i < 10000 ; i++){
ps.setInt(1,i);
ps.setString(2,"tom" + i);
ps.setInt(3,i % 100);
//注意这里执行的是更新操作
ps.executeUpdate();
}
//提交
con.commit();
ps.close();
con.close();
long time = System.currentTimeMillis() - start;
System.out.println(time);//928
}
3、prepared statement 批处理
@org.junit.Test
public void testpreparedstatement() throws Exception {
long start = System.currentTimeMillis();
//创建连接
String driverClass = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/mysql_jdbc";
String username = "root";
String password = "root";
Class.forName(driverClass);
Connection con = DriverManager.getConnection(url, username, password);
//关闭自动提交
con.setAutoCommit(false);
//创建预处理语句
String sql = "insert into student values( ?,?,?)";
PreparedStatement ps = con.prepareStatement(sql);
for(int i = 1; i < 100000 ; i++){
ps.setInt(1,i);
ps.setString(2,"tom" + i);
ps.setInt(3,i % 100);
ps.addBatch();//放在set的后面
if(i % 200 == 0 ){
ps.executeBatch();
}
}
ps.executeBatch();
//提交
con.commit();
ps.close();
con.close();
long time = System.currentTimeMillis() - start;
System.out.println(time);//5351
}
欢迎关注我的公众号:小秋的博客
CSDN博客:https://blog.csdn.net/xiaoqiu_cr
github:https://github.com/crr121
联系邮箱:rongchen633@gmail.com
有什么问题可以给我留言噢~