COMMIT OR conn.setAutoCommit(true)

后端 未结 2 1832
别那么骄傲
别那么骄傲 2020-12-10 14:02

I have noticed some programmer using COMMIT other using conn.setAutoCommit(true); to end the transaction or roll back so what are the benefits of u

2条回答
  •  有刺的猬
    2020-12-10 14:12

    The usage of conn.setAutoCommit(); applies to the connection and gives you the possibility to execute X queries in a single transaction, or use one single transaction per execute

    As the API describes:

     void setAutoCommit(boolean autoCommit)
                        throws SQLException
    

    Sets this connection's auto-commit mode to the given state. If a connection is in auto-commit mode, then all its SQL statements will be executed and committed as individual transactions. Otherwise, its SQL statements are grouped into transactions that are terminated by a call to either the method commit or the method rollback. By default, new connections are in auto-commit mode

    For a simple case:

    conn.setAutoCommit(false); 
    statement.executeQuery(query); 
    statement.commit();
    

    will be the same as:

    conn.setAutoCommit(true); 
    statement.executeQuery(query);
    

提交回复
热议问题