JDBC and Oracle conn.commit and conn.setAutocommit not working properly

前端 未结 4 1415
-上瘾入骨i
-上瘾入骨i 2021-01-12 15:52

I have made a DBManager class as shown below

public class DBManager {


      public static String DRIVER = \"oracle.jdbc.driver.OracleDriver\";
      public         


        
相关标签:
4条回答
  • 2021-01-12 16:23

    TRUNCATE TABLE basically doesn't allow commit/rollback in the normal way. As per this documentation:

    Because a Truncate is DDL it issues a COMMIT before it acts and another COMMIT afterward so no rollback of the transaction is possible.

    If you want to do this as part of a transaction, use DML instead - e.g. a normal DELETE FROM ... statement.

    0 讨论(0)
  • 2021-01-12 16:30

    TRUNCATE is a Data Definition Language (DDL) command which commits implicitly. It wouldn't have committed anything, had you used the DELETE statement instead.

    // Deletes ALL Rows; No WHERE Clause
    pstmnt.executeQuery("DELETE FROM bd_vehicles_temp_");
    

    The reason TRUNCATE is a DDL statement is that it removes the table data directly without copying it into the Rollback Tablespace. That's why TRUNCATE is faster but cannot be rolled back.

    EDIT : (Why my INSERTs are committing as well?)

    That's because you're closing your Connection without calling Connection#rollback().

    If a Connection is closed without an explicit commit or a rollback; JDBC does not mandate anything in particular here and hence the behaviour is dependent on the database vendor. In case of Oracle, an implict commit is issued.

    It is strongly recommended that an application explicitly commits or rolls back an active transaction prior to calling the close method. If the close method is called and there is an active transaction, the results are implementation-defined.

    SO, just rollback() your changes before closing your Connection in the finally block

    pstmnt = conn.createStatement();
    
    pstmnt.executeQuery("DELETE FROM bd_vehicles_temp_1");
    System.out.println("Query Executed");
    
    conn.rollback();
    System.out.println("Changes rolled back");
    
    0 讨论(0)
  • 2021-01-12 16:31

    Oracle truncate command is DDL and it issues commit implicitly. See http://docs.oracle.com/cd/E17952_01/refman-5.5-en/truncate-table.html

    0 讨论(0)
  • 2021-01-12 16:35

    Autocommit behavior depends on the underlying database you use. An unfortunately in your case Oracle's JDBC driver commits on close() by default.

    0 讨论(0)
提交回复
热议问题