如何实现批量添加batch版本二
url添加的一句话
问号请求参数
?rewriteBatchedStatements=true
代码:
package test_path;
import org.junit.Test;
import java.sql.*;
public class MoHuAndDeleteTest {
@Test
public void testMoMu(){
long start = System.currentTimeMillis();
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
try{
//1、注册驱动
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test1?rewriteBatchedStatements=true",
"root", "root");
//循环创建10000次预编译对象
ps=conn.prepareStatement("insert into t_user values(null,?,?)");
for (int i = 1; i < 10000; i++) {
ps.setObject(1,"admin"+i);
ps.setObject(2,i+"pwd");
//将这200条sql语句攒起来
ps.addBatch();
}
//统一执行
ps.executeBatch();
long end = System.currentTimeMillis();
System.out.println("使用executeBatch在预编译对象中将sql语句攒起来花费时间:"+(end-start));
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally {
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
传统方式代码:
package test_path;
import org.junit.Test;
import java.sql.*;
public class MoHuAndDeleteTest {
@Test
public void testMoMu(){
long start = System.currentTimeMillis();
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
try{
//1、注册驱动
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test1",
"root", "root");
//循环创建10000次预编译对象
ps=conn.prepareStatement("insert into t_user values(null,?,?)");
for (int i = 1; i < 200; i++) {
ps.setObject(1,"admin"+i);
ps.setObject(2,i+"pwd");
ps.executeUpdate();
}
long end = System.currentTimeMillis();
System.out.println("使用传统方式批量添加花费时间:"+(end-start));
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally {
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
本文地址:https://blog.csdn.net/qq_41709577/article/details/110677404