若是普通的转账操作我们能想到的就是运用两次update
public static void transferAccounts(int id1,int id2,int money)//id为id1的人向id为id2的人转账money元
{
Connection con=null;
PreparedStatement pstmt1=null;
PreparedStatement pstmt2=null;
ResultSet rs=null;
try {
con=JDBCUtils.getConnection();
String sql="update student set money=money-? where id=?";
pstmt1=con.prepareStatement(sql);
pstmt1.setInt(1, money);
pstmt1.setInt(2, id1);
pstmt1.executeUpdate();
//String s=null;
//s.charAt(2); 这是我们设置的错误,若不用事务,便会发现数据库中的money只有减少,没有增加
sql="update student set money=money+? where id=?";
pstmt2=con.prepareStatement(sql);
pstmt2.setInt(1, money);
pstmt2.setInt(2, id2);
pstmt2.executeUpdate();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
JDBCUtils.close(con, pstmt1, rs);
try {
pstmt2.close();
} catch (Exception e2) {
// TODO: handle exception
}
}
}
但是这种操作是有缺点的,比如当id1的money减少后,在id2的money还未增加前发生了不知名错误,从而导致下面的代码都无法执行,那么就会导致不好的后果,类似于银行存取钱,我们把钱存到银行去,但账户上没变,那岂不是很荒谬?
因此要解决这个问题,我们运用事务。即将这两个操作连在一起,这两个操作要么全都执行,要么全都不执行,具体代码如下:
//关键语句只有两句
con.setAutoCommit(false);//开启事务
con.commit();//提交事务
//将我们想要连接在一起的操作放在这两行代码之间
完整代码如下:
public static void transferAccounts(int id1,int id2,int money)//id为id1的人向id为id2的人转账money元
{
Connection con=null;
PreparedStatement pstmt1=null;
PreparedStatement pstmt2=null;
ResultSet rs=null;
try {
con=JDBCUtils.getConnection();
con.setAutoCommit(false);//开启事务
String sql="update student set money=money-? where id=?";
pstmt1=con.prepareStatement(sql);
pstmt1.setInt(1, money);
pstmt1.setInt(2, id1);
pstmt1.executeUpdate();
sql="update student set money=money+? where id=?";
pstmt2=con.prepareStatement(sql);
pstmt2.setInt(1, money);
pstmt2.setInt(2, id2);
pstmt2.executeUpdate();
con.commit();//提交事务
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
JDBCUtils.close(con, pstmt1, rs);
try {
pstmt2.close();
} catch (Exception e2) {
// TODO: handle exception
}
}
}