/*
使用PrepareStatement数据批量操作
* update、delete本身就具有批量操作的效果。
* 此时的批量操作,主要指的是批量插入。使用PreparedStatement如何实现更高效的批量插入?
* 题目:向goods表中插入20000条数据
* CREATE TABLE goods(
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(25)
);
*/
// 方式一
@Test
public void insertTest1() {
Connection conn=null;
PreparedStatement ps=null;
try {
conn= JDBC_curd.getConnection();
String sql="insert into goods(name) values (?)";
ps =conn.prepareStatement(sql);
long start = System.currentTimeMillis();
for (int i = 0; i <1000 ; i++) {
ps.setObject(1,"name_"+(i+1));
ps.execute();
}
long end = System.currentTimeMillis();
System.out.println((end-start)+"ms" );
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
JDBC_curd.closeConnection(conn,ps);
}
}
2433ms (1000条数据)
/*
* 批量插入的方式二:
* 1.addBatch()、executeBatch()、clearBatch()
* 2.mysql服务器默认是关闭批处理的,我们需要通过一个参数,让mysql开启批处理的支持。
* ?rewriteBatchedStatements=true 写在配置文件的url后面
*
*
* TRUNCATE TABLE goods;
*/
@Test
public void insertTest2() {
Connection conn=null;
PreparedStatement ps=null;
try {
conn= JDBC_curd.getConnection();
String sql="insert into goods(name) values (?)";
ps =conn.prepareStatement(sql);
long start = System.currentTimeMillis();
for (int i = 0; i <1000000 ; i++) {
ps.setObject(1,"name_"+(i+1));
ps.addBatch();
if (i%500==0){
ps.executeBatch();
ps.clearBatch();
}
}
long end = System.currentTimeMillis();
System.out.println((end-start)+"ms" );
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
JDBC_curd.closeConnection(conn,ps);
}
}
10226ms (一百万条数据)
// 方式3 设置连接不允许自动提交数据
@Test
public void insertTest3() {
Connection conn=null;
PreparedStatement ps=null;
try {
conn= JDBC_curd.getConnection();
String sql="insert into goods(name) values (?)";
ps =conn.prepareStatement(sql);
//设置不允许自动提交数据
conn.setAutoCommit(false);
long start = System.currentTimeMillis();
for (int i = 0; i <1000000 ; i++) {
ps.setObject(1,"name_"+(i+1));
ps.addBatch();
if (i%500==0){
ps.executeBatch();
ps.clearBatch();
}
}
//提交数据
conn.commit();
long end = System.currentTimeMillis();
System.out.println((end-start)+"ms" );
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
JDBC_curd.closeConnection(conn,ps);
}
}
4283ms (一百万条数据)