需要实现在user_table表中AA给BB转账1000
AA.balance-1000同时BB.balance+1000
两个事情必须要么执行,要么不执行,这就是事务
没有加事务的做法:
public static void updateCustomer(String sql,Object... args){
Connection connection = null;
PreparedStatement ps = null;
try {
connection = JDBCUtils.getConnection();
ps = connection.prepareStatement(sql);
for(int i=0;i<args.length;i++){
ps.setObject(i+1,args[i]);
}
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtils.closeResource(connection,ps);
}
}
@Test
public void test01(){
String sql1="update user_table set balance=balance-1000 WHERE `user`=?";
Common.updateCustomer(sql1,"AA");
System.out.println(10/0);
String sql2="update user_table set balance=balance+1000 WHERE `user`=?";
Common.updateCustomer(sql2,"BB");
System.out.println("转账成功");
}
考虑事务以后的代码实现update:
public static void updateCustomerTx(Connection connection,String sql,Object... args){
PreparedStatement ps = null;
try {
ps = connection.prepareStatement(sql);
for(int i=0;i<args.length;i++){
ps.setObject(i+1,args[i]);
}
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtils.closeResource(null,ps);
}
}
@Test
public void test2() {
Connection connection=null;
try {
connection = JDBCUtils.getConnection();
System.out.println("连接的默认提交方式:" + connection.getAutoCommit());
connection.setAutoCommit(false);
String sql1 = "update user_table set balance=balance-1000 WHERE `user`=?";
Common.updateCustomerTx(connection, sql1, "AA");
System.out.println(10/0);
String sql2 = "update user_table set balance=balance+1000 WHERE `user`=?";
Common.updateCustomerTx(connection, sql2, "BB");
System.out.println("转账成功");
connection.commit();
} catch (Exception e) {
try {
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
} finally {
connection.setAutoCommit(false);
JDBCUtils.closeResource(connection,null);
}
}