批处理概述
当与数据库进行交互时,每执行一条执行SQL语句,就会和数据库进行一次连接,每进行一次连接会很耗费时间,因此批处理会是你的好伙伴哟。
1、批量增删改方法
批量增删改可以减少与数据库的连接次数,从而节省时间(连接数据库需要耗费时间),如果不这么做的话,每执行一条执行SQL语句,就会和数据库进行一次连接,会很浪费时间。
PreparedStatement.addBatch() //加入批处理包
PreparedStatement.executeBatch() //把批处理包中所有sql,一次性发送给数据库服务器
并不是直接调用这些方法就可以进行批量增删改的,mysql需要通过连接参数开启批处理功能,这些参数默认时是false,也就是把url的参数写为rewriteBatchedStatements=true,即url写为jdbc:mysql://localhost:3306/test?rewriteBatchedStatements=true。
代码演示
向表中插入100000条记录,该表有两列,两列都是要插入名字,并输出所用的时间
用批量方法
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Batch {
//要打开增删改批处理需要把参数rewriteBatchedStatements设为true
private static final String URL="jdbc:mysql://localhost:3306/school?rewriteBatchedStatements=true";
private static final String USERNAME="root";
private static final String PASSWORD="root";
public static void main(String[] args) {
try (Connection conn=DriverManager.getConnection(URL,USERNAME,PASSWORD)){
try(PreparedStatement psmt = conn.prepareStatement("insert into uname(name1,name2) values(?,?)")){
//开始插入时的毫秒值
long start = System.currentTimeMillis();
//循环插入10万条记录
for (int i = 1; i <= 100000; i++) {
psmt.setString(1,"jack"+i);
psmt.setString(2,"jack"+i);
//添加到缓存中
psmt.addBatch();
//执行缓存中一万条插入记录
if(i%10000==0){
psmt.executeBatch();
}
}
//结束插入的毫秒值
long end=System.currentTimeMillis();
//输出整个插入过程中用了多少秒
System.out.println("一共用了"+(end-start)/1000+"秒");
}
}catch(SQLException e){
e.printStackTrace();
}
}
}
结果
Fri Dec 28 20:27:50 CST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
一共用了11秒
不用批处理
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class NoBatch {
private static final String URL="jdbc:my