do I need a connection.commit() after executeBatch()?

China☆狼群 提交于 2019-12-21 05:08:23

问题


I have to check the code of a fellow coworker and I stumble on this piece of code:

private void pdate(JdbcTemplate jdbcTemplate, List<Long> saisineIdsToUpdate,Connection connection) throws SQLException {
    String sqlUpdate = "UPDATE SAISINES SAI WHERE SAI.IDSAISINE = ?"; //request simplified

    PreparedStatement psUpdate = connection.prepareStatement(sqlUpdate);

    for (Long saisineId : saisineIdsToUpdate) {
        psUpdate.setLong(1, saisineId );
        psUpdate.addBatch();

    }
    psUpdate.executeBatch();
    psUpdate.close();

The code works, the updates are done correctly, but I cannot find the trace of a connection.commit(); I wonder how it can work without the commit - could someone explain why ?


回答1:


As explained here, JDBC-drivers commonly use autocommit, you can enable database-traces via DBMS-driver specific settings like showSQL or generateDDL in JPA.

To enable manual- transaction support instead of the auto-commit mode that the JDBC driver uses by default, use the Connection object's setAutoCommit() method. If you pass a boolean false to setAutoCommit( ), you turn off auto-commit. You can pass a boolean true to turn it back on again.




回答2:


if you set auto-commit on your connection object to false then we have to commit the transaction manually

connection.setAutoCommit(false);
// your code goes here
connection.commit();

if you don't set auto-commit then default its value is true and it will commit each record



来源:https://stackoverflow.com/questions/26888272/do-i-need-a-connection-commit-after-executebatch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!