JDBC 批处理:
当需要向数据库发送一批 SQL 语句执行时,应避免向数据库一条条的发送执行,而应采用 JDBC 的批处理机制,以提升执行效率。
实现批处理有两种方式
- 第一种方式:
- statement 批处理
@Test
public void show(){
Connection conn =null;
Statement stmt = null;
try {
conn = JDBCUtil.getConnection();
stmt = conn.createStatement();
//添加批次
for(int i = 1 ;i <=10000 ; i++){
String sql ="insert into
tb_user(username,password)values( '"+i+"','19')";
stmt.addBatch(sql);
//一次性向数据库添加 3000
if(i%3000 == 0){
//执行批次
stmt.executeBatch();
//清空批次
stmt.clearBatch();
}
}
/执行余下批次
stmt.executeBatch();
//清空批次
stmt.clearBatch();
} catch (SQLException e) { e.printStackTrace();
}finally{
JDBCUtil.close(conn, stmt);
}
}
Statement.addBatch(sql)
执行批处理 SQL 语句
executeBatch()方法:执行批处理命令
clearBatch()方法:清除批处理命令
采用 Statement.addBatch(sql)方式实现批处理:
优点:可以向数据库发送多条不同的 sql 语句。
缺点: SQL 语句没有预编译。当向数据库发送多条语句相同,但仅参数不同的
SQL 语句时,需重复写上很多条 SQL 语句。例如:
Insert into user(name,password) values(‘aa’,’111’);
Insert into user(name,password) values(‘bb’,’222’);
Insert into user(name,password) values(‘cc’,’333’);
Insert into user(name,password) values(‘dd’,’444’);
-
第二种方式:
-
preparestatement 批处理
-
优点:
-
发送的是与编译后的sql语句,执行效率高
-
缺点:
-
只能应用在sql语句相同,但是参数不同的批处理中,因此此种形式的批处理经常用于在同一表中批量插入相同的数据,或者批量更新表中的数据。
PreparedStatement ps = null; Connection con = null; Savepoint sp = null; try{ con = TestC3P0.getConnectionTest(); String sql = "insert into bank(name,money) values(?,?)"; ps = con.prepareStatement(sql); con.setAutoCommit(false); for (int i = 0; i < 100; i++) { ps.setString(1, "xrn"); ps.setDouble(2, 100); ps.addBatch(); if (i%30 ==0) { ps.executeBatch();//批处理,一次三十条 ps.clearBatch();//清理批处理 } } ps.executeBatch();//存入剩余的数据 ps.clearBatch(); con.commit(); }catch(Exception a){ a.printStackTrace(); }finally{ try { con.setAutoCommit(true); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
两种批处理的区别:
1.prestatement的效率比前者高
2.在使用PreparedStatement对象执行SQL命令时,命令被数据库进行编译和解析,然后被放到命令缓冲区.然后,每当执行同一个PreparedStatement对象时,它就会被再解析一次,但不会被再次编译.在缓冲区中可以发现预编译的命令,并且可以重新使用.
2278

被折叠的 条评论
为什么被折叠?



