import java.sql.*;public class TestBatch { public static void main(String[] args) {
Connection co = null;
Statement cs = null;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
co = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:myora1","scott","tiger");
cs = co.createStatement();
cs.executeUpdate("insert into dept2 values(1,'wjf','nanjing')");
cs.executeUpdate("insert into dept2 values(2,'yjq','nanjing')");
/*视频里面说,如果执行多条更新语句,要用cs.addBatch("insert into dept2 values(1,'wjf','nanjing')");进行批处理,否则要创建多个Statement实例,但是我试了一下,只创建了一个Statement,
同样能往数据库里面插入两条语句,这是为什么,如何理解?*/
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch(SQLException e){
e.printStackTrace();
}finally{
try{
if(cs != null){
cs.close();
cs = null;
}
if(co != null){
co.close();
co = null;
}
}catch(SQLException e){
e.printStackTrace();
}
}
}
}
执行的就是前面你用addBatch()添加的sql数组
前提是数据库支持sql的批量处理
用connection.getMetaData.supportBatchUpdates()可以判断是否支持
Adds the given SQL command to the current list of commmands for this Statement object. The commands in this list can be executed as a batch by calling the method executeBatch. 用的时候是这样的 cs.addBatch("insert into dept2 values(1,'wjf','nanjing')");
cs.addBatch("insert into dept2 values(2,'yjq','nanjing')");
cs.executeBatch();
区别是,直接update是发送两次请求,batch是发送一起请求
co.setAutoCommit(false)加上
再理解下
Statement stat=conn.createStatement();
stat.addBatch("...");
while(..)
stat.addBatch("...");
stat.executeBatch();批量执行的好处是更有效率,当其中一个语句发生异常时,取决于驱动,有的是继续执行(忽略),有的是不再继续执行所以
先conn.setAutoCommit(false);
然后再
stat.executeBatch();
如果没有异常
conn.commit();
否则
conn.rollBack();
stat.addBatch("insert...");
stat.addBatch("update...");