若此時 Connection 沒有被關閉, 則需要恢復其自動提交狀態
常用的代碼結構
public void test(String sql, Object... args)
{
Connection conn = null;
PreparedStatement prepareStatement = null;
try
{
conn = getConn();
// 事物處理前,取消Connection的默認提交行為
conn.setAutoCommit(false);
prepareStatement = conn.prepareStatement(sql);
for (int i = 0; i < args.length; i++)
{
prepareStatement.setObject(i + 1, args[i]);
}
prepareStatement.executeUpdate();
// 事物處理:如果事物處理成功則提交事物
conn.commit();
}
catch (Exception e)
{
e.printStackTrace();
try
{
// 事物處理:如果出現異常 則在catch塊中回滾事物
conn.rollback();
}
catch (SQLException e1)
{
e1.printStackTrace();
}
}
finally
{ // 釋放數據庫資源
releaseSource(prepareStatement, conn, null);
}
}