prepareStatement和Statement執行批處理的執行情況

z1340954953發表於2018-04-04

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



相關文章