1. 转账操作 (不添加事务)
public static void transfer(String username1,String username2,int amount) { Connection con = null; PreparedStatement stmt1 = null; PreparedStatement stmt2 = null; try { con = JDBCUtils.getConnection(); String sql = "update user set balance = balance - ? where username = ?"; stmt1 = con.prepareStatement(sql); stmt1.setInt(1, amount); stmt1.setString(2,username1); stmt1.executeUpdate(); // 如果在这里出现异常, 则转账人会损失金钱 sql = "update user set balance = balance + ? where username = ?"; stmt2 = con.prepareStatement(sql); stmt2.setInt(1, amount); stmt2.setString(2,username2); stmt2.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { JDBCUtils.close(stmt2, stmt1, con); } }
2. 转账操作 (添加事务)
public static void transfer(String username1,String username2,int amount) { Connection con = null; PreparedStatement stmt1 = null; PreparedStatement stmt2 = null; try { con = JDBCUtils.getConnection(); con.setAutoCommit(false); // 开启事务 String sql = "update user set balance = balance -? where username =?"; stmt1 = con.prepareStatement(sql); stmt1.setInt(1, amount); stmt1.setString(2,username1); stmt1.executeUpdate();
// 在"事务"中, 如果有代码执行不成功,"事务"就不会执行
sql = "update user set balance = balance + ? where username =?"; stmt2 = con.prepareStatement(sql); stmt2.setInt(1, amount); stmt2.setString(2,username2); stmt2.executeUpdate(); con.commit(); // 提交事务 } catch (Exception e) { e.printStackTrace(); } finally { JDBCUtils.close(stmt2, stmt1, con); } }