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?