[英]Distributing statements for a JDBC transaction in multiple methods
我需要做一個相當長的JDBC事務。 我可以像這樣通過多種方法分發交易所需的語句嗎?
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();
}
一句話:是的。
長期運行的事務可能會有害。 例如, 在SQL Server中,它們可能導致事務日志填充 。
我沒有發現任何問題。 重要的是要確保在完成連接時即關閉連接。 我將確保打開連接的代碼使用與關閉連接相同的方法,因為連接泄漏可能很難追蹤。
附帶說明一下,我喜歡使用Spring的JDBC功能。 它可以為您管理連接,並且非常易於使用。 http://static.springsource.org/spring/docs/current/spring-framework-reference/html/jdbc.html
要糾正的兩件事:
java.sql.Connection
上的rollback()
和close()
方法都拋出SQLException
。 您應該將兩個調用都包裝在try / catch塊中,以確保正確操作。 (在您的情況下,代碼甚至無法按編寫的方式進行編譯。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.