****************************************************************
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();
}
}
}
}