Reputation: 2338
I have multiple prepared statements. Do I need to execute 'connection.commit' for every statement or call only once after the last statement?
Connection connection = datasource.getConnect();
connection.setAutoCommit(false);
PreparedStatement pstmt1 = connection.prepareStatement(query1);
pstmt1.executeUpdate();
connection.commit();
PreparedStatement pstmt2 = connection.prepareStatement(query2);
pstmt2.executeUpdate();
connection.commit();
PreparedStatement pstmt3 = connection.prepareStatement(query3);
pstmt3.executeUpdate();
connection.commit();
Or
Connection connection = datasource.getConnect();
connection.setAutoCommit(false);
PreparedStatement pstmt1 = connection.prepareStatement(query1);
pstmt1.executeUpdate();
PreparedStatement pstmt2 = connection.prepareStatement(query2);
pstmt2.executeUpdate();
PreparedStatement pstmt3 = connection.prepareStatement(query3);
pstmt3.executeUpdate();
connection.commit();
Thanks.
Upvotes: 2
Views: 4549
Reputation: 22915
If you set autocommit = false
, then you can choose when you commit the transaction. Where that is best done, only you can judge as it depends upon atomicity, transaction isolation etc.
That's the whole point of exposing the autoCommit property to you, the "end-user", so you have control over how changes relate to/dependent upon each other.
What you can't do (I'm pretty sure - it's been a while since I programmed in JDBC directly) is issue 2 commit commands without any other command in between.
Upvotes: 6