I need to do a considerably long JDBC transaction. Can I dist开发者_JS百科ribute the statements required for the transaction in multiple methods, like this?
try {
// ... Get connection
// Start transaction
connection.setAutoCommit(false);
// In every one of these methods a series of statements is executed
// All methods throw a SQLException which is caught here for rollback
// Every method takes this connection as an argument
method1(connection);
method2(connection);
// ...
methodN(connection);
// Commit all changes done inside the methods
connection.commit();
} catch (SQLException e) {
connection.rollback();
} finally {
connection.setAutoCommit(true);
connection.close();
}
In a word: yes.
Incidentally long running transactions can be harmful. For example, in SQL Server, they can cause the transaction log to fill.
I don't see any problem with this. The important thing is to make sure you close the connection when you are done, which are you doing there. I would make sure that the code that opens the connection is in the same method where it closes it, because connection leaks can be really tough to track down.
As a side note, I like to use Spring's JDBC functionality. It manages connections for you and is really easy to use. http://static.springsource.org/spring/docs/current/spring-framework-reference/html/jdbc.html
Two things to correct:
Both the rollback()
and close()
methods on java.sql.Connection
throw SQLException
. You should wrap both calls in try/catch blocks to ensure proper operation. (In your case, the code won't even compile as written.)
精彩评论