核心思想是两个操作都放到一个connection中,这个是要点。
public class JavaTransactionCtl {
public static void main(String[] args) {
Connection connection=JdbcUtil.getCconnection();
connection.setAutoCommit(false);
outMoney(connection,"b",100);
inMoney(connection,"a",100);
connection.commit();
JdbcUtil.CloseResource(connection,PreparedStatement,ResultSet:null);
}
public static void inMoney(Connection connection,String name,double money) throws SQLException {
PreparedStatement preparedStatement=null;
String sql="update account set money=money+? where name=?";
preparedStatement=connection.prepareStatement(sql);
preparedStatement.setDouble(1,money);
preparedStatement.setString(2,name);
preparedStatement.executeQuery();
}
public static void outMoney(Connection connection,String name,double money) throws SQLException{
PreparedStatement preparedStatement=null;
String sql="update account set money=money-? where name=?";
preparedStatement=connection.prepareStatement(sql);
preparedStatement.setDouble(1,money);
preparedStatement.setString(2,name);
preparedStatement.executeQuery();
}
}



