1. 程式人生 > >JDBC 批處理

JDBC 批處理

!= count test .exe false upd code exceptio nal

主要是是

addBatch ,executeBatch ,clearBatch 三個方法.

官方示例代碼:

public void batchUpdate() throws SQLException {

    Statement stmt = null;
    try {
        this.con.setAutoCommit(false);//關閉commit
        stmt = this.con.createStatement();//創建statement

        stmt.addBatch(
            "INSERT INTO COFFEES " +
            "VALUES(‘Amaretto‘, 49, 9.99, 0, 0)");

        stmt.addBatch(
            "INSERT INTO COFFEES " +
            "VALUES(‘Hazelnut‘, 49, 9.99, 0, 0)");

        stmt.addBatch(
            "INSERT INTO COFFEES " +
            "VALUES(‘Amaretto_decaf‘, 49, " +
            "10.99, 0, 0)");

        stmt.addBatch(
            "INSERT INTO COFFEES " +
            "VALUES(‘Hazelnut_decaf‘, 49, " +
            "10.99, 0, 0)");

        int [] updateCounts = stmt.executeBatch();//編譯多條sql語句
        this.con.commit();//commit,之後sql語句去哪不執行

    } catch(BatchUpdateException b) {
        JDBCTutorialUtilities.printBatchUpdateException(b);
    } catch(SQLException ex) {
        JDBCTutorialUtilities.printSQLException(ex);
    } finally {
        if (stmt != null) { stmt.close(); }
        this.con.setAutoCommit(true);
    }
}

  

JDBC 批處理