2011-09-09 23 views
2

我需要執行相當長的JDBC事務。我可以使用多種方法分配交易所需的報表嗎?以多種方式分配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(); 
} 
+0

是什麼讓你覺得這*不會工作? –

+0

我不確定方法內部的Statement對象的範圍是否以任何方式相關。在方法返回後,語句不存在,我不知道程序運行時執行的查詢是如何「存儲」的。它們是「綁定」到Connection對象而不是Statement對象的? –

回答

1

我沒有看到任何問題。重要的是確保你完成後關閉連接,你在那裏做什麼。我會確保打開連接的代碼與它關閉它的方法相同,因爲連接泄漏可能非常難以追查。

作爲便箋,我喜歡使用Spring的JDBC功能。它爲您管理連接,非常易於使用。 http://static.springsource.org/spring/docs/current/spring-framework-reference/html/jdbc.html

+1

感謝您的鏈接!我可以嘗試使用Spring。 –

+1

我會第二次(和第三次)Spring的建議。爲什麼要自己寫樣板文件?他們做得很漂亮。 – duffymo

1

兩件事情來糾正:

無論是rollback()close()方法上java.sql.ConnectionSQLException。您應該將這兩個調用包裝在try/catch塊中以確保正確操作。 (在你的情況下,代碼甚至不會像編寫的那樣編譯。)

+0

感謝您的評論! –