批量插入
package com.atguigu.api.preparedStatement;
import org.junit.Test;
import java.sql.*;
public class PSOtherPart {
//使用普通循环插入 10000 条数据 --> 21832ms
@Test
public void testInsert() throws Exception {
//1.注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2.获取数据库连接
Connection connection = DriverManager.getConnection("jdbc:mysql:///atguigu?user=root&password=123456");
//3.编写sql语句
String sql = "insert into t_user(account,password,nickname) values(?,?,?);";
//4.创建PreparedStatement
//传入Statement.RETURN_GENERATED_KEYS 从而在结果集中携带数据库自增长主键
PreparedStatement preparedStatement = connection.prepareStatement(sql);
//5.占位符赋值
long start = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
preparedStatement.setObject(1,"zzz" + i);
preparedStatement.setObject(2,"11111" + i);
preparedStatement.setObject(3,"hehe" + i);
//6.发送SQL语句,并获取结果
preparedStatement.executeUpdate();
}
long end = System.currentTimeMillis();
// 4211 ms
System.out.println("执行10000次数据插入消耗的时间" + (end - start));
//8.关闭资源
preparedStatement.close();
connection.close();
}
/**
* TODO 使用批量插入方式插入 10000 条数据 --> 36118ms
* 1.路径后面添加 ?rewriteBatchedStatement=true 表示允许批量插入
* 2.insert 语句不能添加 ; 结束
* 3.不是每次执行,而是每次添加到批中 addBatch()
* 4.遍历添加完毕后,统一批量执行 preparedStatement.executeBatch();
*/
@Test
public void testBatchInsert() throws Exception {
//1.注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2.获取数据库连接
//批量插入需要在url中添加 rewriteBatchStatement=true 允许批量操作
Connection connection = DriverManager.getConnection("jdbc:mysql:///atguigu?rewriteBatchedStatement=true","root","123456");
//3.编写sql语句
String sql = "insert into t_user(account,password,nickname) values(?,?,?)";
//4.创建PreparedStatement
//传入Statement.RETURN_GENERATED_KEYS 从而在结果集中携带数据库自增长主键
PreparedStatement preparedStatement = connection.prepareStatement(sql);
//5.占位符赋值
long start = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
preparedStatement.setObject(1,"aaa" + i);
preparedStatement.setObject(2,"22222" + i);
preparedStatement.setObject(3,"haha" + i);
//6.发送SQL语句,并获取结果
//preparedStatement.executeUpdate();
preparedStatement.addBatch(); //不执行,而是追加数据到 values 后
}
//全部追加完毕后,一次插入 -> 执行批量操作
preparedStatement.executeBatch();
long end = System.currentTimeMillis();
// 4211 ms
System.out.println("执行10000次数据插入消耗的时间" + (end - start));
//8.关闭资源
preparedStatement.close();
connection.close();
}
}
标签:preparedStatement,setObject,批量,JDBC7,System,插入,sql
From: https://www.cnblogs.com/Ashen-/p/17048960.html