问题遇到的现象和发生背景
想模拟一个转账业务,数据库中只有A(余额20000)和B(余额0),使用Update语句将二者余额都变为10000。已经关闭了事务自动提交,设置了结尾手动提交和事务回滚。但故意将B写成M后,A的钱还是会减少到10000
问题相关代码,请勿粘贴截图
conn = DriverManager.getConnection(url,user,password);
conn.setAutoCommit(false);
String sql = "update t_act set balance = ? where actno = ?";
ps = conn.prepareStatement(sql);
ps.setDouble(1,10000);
ps.setString(2,"m");
int count = ps.executeUpdate();
ps.setDouble(1,10000);
ps.setString(2,"M");
count += ps.executeUpdate();
conn.commit();
System.out.println(count == 2? "转账成功":"转账失败");
} catch (ClassNotFoundException | SQLException e) {
if(conn != null){
try {
conn.rollback();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
e.printStackTrace();
}finally {
if(ps != null){
try {
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
运行结果及报错内容
转账失败,但A的钱还是少了