preparestatement因为有预编译机制,每次执行相同sql的预编译,只会执行一次,下次只要设置参数就行,
适合相同sql的批处理
如果一定要多次编译不同sql,执行批处理的话,只会执行一个sql
public static void main(String[] args) throws Exception {
ConnManager.initCurrPool();
Connection dbConn = ConnManager.getConnByCurr();
dbConn.setAutoCommit(false);
PreparedStatement pstm = null;
pstm = dbConn
.prepareStatement(" update tc_day_summary set fund_head = 1 where work_day = '20180319' ");
pstm.addBatch();
pstm = dbConn
.prepareStatement(" update take_order_addr set cust_name ='项羽' where aip_no = 'AIP100000721' ");
pstm.addBatch();
int[] executeBatch = pstm.executeBatch();
System.out.println(executeBatch.length);
// dbConn.commit();
}
输出结果:1
如果需要多个不同的sql来执行批处理使用statement,上面的改为:
public static void main(String[] args) throws Exception {
ConnManager.initCurrPool();
Connection dbConn = ConnManager.getConnByCurr();
dbConn.setAutoCommit(false);
Statement stmt = null;
stmt = dbConn.createStatement();
stmt.addBatch("update tc_day_summary set fund_head = 1 where work_day = '20180319' ");
stmt.addBatch(" update take_order_addr set cust_name ='项羽' where aip_no = 'AIP100000721' ");
int[] executeBatch = stmt.executeBatch();
System.out.println(executeBatch.length);
// dbConn.commit();
}
输出结果: 2