批处理:
当我们有多条sql语句需要发送到数据库执行的时候,有两种发送方式,一种是执行一条发送一条sql语句给数据库,另一种是发送一个sql集合给数据库,也就是发送一批sql语句到数据库。很显然两者的数据库执行效率是不同的,我们发送批处理sql的时候数据库执行效率要高。所以我们有必要掌握mysql数据库的sql批处理发送方式方法。
批处理的两种方式:Statement接口和PreparedStatement接口
具体方法:
1、Statement:
addBatch(String sql);//添加批处理
executeBatch();//执行批处理
2、 PreparedStatement;
addBatch();//添加批处理
executeBatch();//执行批处理
例如:
第一种方式:
/**使用批处理插入1000条记录*/
public void testStatement02(){
try {
Statement stat = conn.createStatement();
conn.setAutoCommit(false);
for(int i=0;i<5000;i++) {
int account_idcard = (int)(Math.random()*500);
double money = Math.random()*1000;
int account_phone =(int)(Math.random()*900);
String sql = "insert into account_info values(null,'"+account_idcard+"',"+money+",'"+account_phone+"')";
stat.addBatch(sql);//添加批处理
if(i%400==0) {
stat.executeBatch();//执行一次批处理
conn.commit();
stat.clearBatch();//清除批处理的缓存
}
}
stat.executeBatch();//将批处理剩余的不满220条记录的一次性执行。
conn.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
第二种方式:
/**使用批处理插入1000条记录*/
public void testPreparedStatement02() {
try {
String sql = "insert into account_info values(null,?,?,?)";
PreparedStatement ps = conn.prepareStatement(sql);
conn.setAutoCommit(false);//取消自动提交
for(int i=0;i<1000;i++) {
String account_idcard = (int)(Math.random()*500)+"";
double money = Math.random()*1000;
String account_phone = (int)(Math.random()*900)+"";
ps.setString(1, account_idcard);
ps.setDouble(2, money);
ps.setString(3, account_phone);
ps.addBatch();//添加批处理
if(i%220==0) {
ps.executeBatch();//执行批处理
conn.commit();//手动提交,每执行一个220条的批处理就相当于完成一个事务。
ps.clearBatch();//清除批处理的缓存
}
}
ps.executeBatch();//将批处理剩余的不满220条记录的一次性执行。
conn.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
采用PreaparedStatement接口实现批处理:
优点:发送的是预编译的sql语句。执行效率高。
缺点:只能应用到sql语句相同,但参数不同的批处理中,因此此种批处理经常用于在同一个表中批量插入数据或者批量更新数据。