/**
*实现事务:Tom 对Jerry 转账500元
*
*/
public class TransactionTest {
public static void update(Connection conn,String sql,Object ... args){
PreparedStatement pstmt = null;
try{
pstmt = conn.prepareStatement(sql);//通过SQL语句 创建PreparedStatement 对象。
//利用 for 循环对 SQL 语句中的 PreparedStatement 占位符 ,更新数据。
for(int i = 0;i < args.length;i++){
pstmt.setObject((i+1), args[i]);
}
//更新执行。
pstmt.executeUpdate();
}catch(Exception e){
e.printStackTrace();
}finally{
//关闭数据库连接。
JDBCTools.release(null, pstmt, null);
}
}
public static void main(String[] args) {
Connection conn = null;
try{
conn = JDBCTools.getConnection();
//取消默认的提交方式
conn.setAutoCommit(false);
String sql = "UPDATE user SET balance = balance - 500 WHERE id = 2000001";
update(conn, sql);
/*此处会 报com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException,Table 'ming.users' doesn't exist
但是,整个事务却没有回滚。*/
sql = "UPDATE users SET balance = balance + 500 WHERE id = 2000002";
update(conn,sql);
//若事务操作正常,则提交事务
conn.commit();
} catch(Exception e){
//若事务操作出现异常,则需要在异常处理中回滚事务
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
} finally{
JDBCTools.release(null, null, conn);
}
}
}