Best Practice for AutoCommit statements in Java for MySQL usage via JDBC

Rob :

Within my Java code I interact with an MySQL database via a JDBC connection. I setup a connection and some statements (for reuse)

            connect = DriverManager.getConnection(connectionstring);            
            statement = connect.createStatement();
            statement2 = connect.createStatement();

For most of the code, statement.executeQuery(query) is fine, but some operations are "blocks", so I need to make sure that they either all go through together, or none of them do. I believe the following code achieves this.

            connect.setAutoCommit(false);
            statement.addBatch(insertquery1);
            statement.addBatch(insertquery2);
            statement.addBatch(insertquery3);
            statement.addBatch(insertquery4);
            statement.executeBatch();
            connect.commit();           
            connect.setAutoCommit(true);

As far as I can tell, the connect calls affect the entire connection, so would impact both statement and statement2. Also, I can seemingly set the AutoCommit values after I created the statement object and it still applies to it. Is this correct? And would it be better practice/more efficient to split them and keep a different connection object just for autocommit calls like below?

            // objects purely for batch operations
            connect = DriverManager.getConnection(connectionstring);            
            connect.setAutoCommit(false);
            statement = connect.createStatement();
            // objects for normal operations
            connect2 = DriverManager.getConnection(connectionstring);           
            connect2.setAutoCommit(true);
            statement2 = connect2.createStatement();

In my application they represent less than 1% of calls, but that percentage does need to be done in batches. What is best practice?

Tim Biegeleisen :

The whole point of setting auto commit to false is so that multiple SQL statements can all run inside the same transaction. And, should anything go wrong with any of your 4 insert statements, the whole transaction would logically be rolled back, so that you don't end up with inconsistent data in your database. The pattern you are already following is best practice:

connect.setAutoCommit(false);
statement.addBatch(insertquery1);
statement.addBatch(insertquery2);
statement.addBatch(insertquery3);
statement.addBatch(insertquery4);
statement.executeBatch();
connect.commit();           
connect.setAutoCommit(true);

That is, it is best practice to return auto commit to being true after you have completed your transaction. This is so that any other part of your code, or perhaps your future code, should someone else inherit it, which still uses the same connection object would receive the default behavior of auto commit being true.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=389284&siteId=1