public class JdbcZhuangzhang {
public static void main(String[] args){
Connection connection=null;
PreparedStatement preparedStatement=null;
//lp转给tj100元
try{
//第一步:得到数据库连接
connection= JDBCUtils.getConnection();
//第二步:开启事务
connection.setAutoCommit(false);
//第三步:准备好转账的SQL语句
String sql1="update account set money=money+? where id=?";
// 第四步:加载sql
//lp转出100
preparedStatement=connection.prepareStatement(sql1);
preparedStatement.setDouble(1,-100);
preparedStatement.setInt(2,1);
preparedStatement.executeUpdate();
//tj转入100
preparedStatement=connection.prepareStatement(sql1);
preparedStatement.setDouble(1,100);
preparedStatement.setInt(2,2);
preparedStatement.executeUpdate();
//第五步:提交事务
connection.commit();
}catch (Exception e){
try{
connection.rollback();
}catch (SQLException ex){
throw new RuntimeException(ex);
}
}finally {
try{
//第六步:关闭资源
JDBCUtils.close(null,preparedStatement,connection);
}catch (SQLException e){
throw new RuntimeException(e);
}
}
}
}
数据库中表数据中lp,tj,xk都1000
idea运行成这样就成功了
运行好了数据库中的表刷新就转账成功了
表数据中lp从自己的1000中给tj100
这样转账就成功了