****************************************************************
1.準備資源
2.啓動事物
3.在事務中執行具體數據訪問操作
4.提交/回滾事務
5.關閉資源,處理異常
*****************不能更加簡單了!!!************************
public class TestDao {
public void save(User user)throws Exception{
Connection connection=null;
PreparedStatement stmt=null;
try {
//1.獲取資源
connection=getConnection();
//2.啓動事務
connection.setAutoCommit(false);
//3.具體數據訪問操作和處理
stmt=connection.prepareStatement("INSERT INTO user(ID,NAME) VALUES(?,?)");
stmt.setInt(1, user.getUserId());
stmt.setString(2, user.getUsername());
stmt.execute();
//4.事務提交
connection.commit();
} catch (Exception e) {
try {
//5.事務回滾
connection.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
throw e;
}finally{
//6.釋放資源
try {
stmt.close();
connection.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}