在Java中使用JDBC開啟事務(wù)的方法是通過Connection對(duì)象的setAutoCommit方法來實(shí)現(xiàn)。默認(rèn)情況下,Connection對(duì)象的autoCommit屬性為true,即自動(dòng)提交事務(wù)。若要開啟事務(wù),需將autoCommit屬性設(shè)置為false,并手動(dòng)提交或回滾事務(wù)。
代碼示例:
Connection conn = null; try {????//?獲取連接
????conn?=?DriverManager.getConnection(url,?username,?password);
????
????//?開啟事務(wù)
????conn.setAutoCommit(false);
????
????//?執(zhí)行SQL語句
????//?…
????
????//?提交事務(wù)
????conn.commit(); }?catch?(SQLException?e)?{
????//?回滾事務(wù)
????if?(conn?!=?null)?{
????????try?{
????????????conn.rollback();
????????}?catch?(SQLException?ex)?{
????????????ex.printStackTrace();
????????}
????}
????e.printStackTrace(); }?finally?{
????//?關(guān)閉連接
????if?(conn?!=?null)?{
????????try?{
????????????conn.close();
????????}?catch?(SQLException?e)?{
????????????e.printStackTrace();
????????}
????} }