天天看点

JDBC--用户A向用户B转账(考虑数据库事务)

//更新数据库的方法,增,删改(考虑数据库事务)
    public static int updateDataTransaction(Connection connection,String sql,Object ...args) throws SQLException, IOException, ClassNotFoundException {
        int count=0;
        //获取预编译的statement对象
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        //填充占位符
        if(args.length!=0){
            for(int i=0;i<args.length;i++){
                preparedStatement.setObject(i+1,args[i]);
            }
        }
        //执行
        count = preparedStatement.executeUpdate();//返回影响的行数
        //关闭资源,暂时 先不关闭数据库连接连接
        releaseResources(null,preparedStatement);
        return count;
    }
           
public class TransferTest1 {
    public static void main(String[] args){
        Connection testConnection=null;
        try {
            //1.获取数据库连接
            testConnection = DatabaseConnectivity.getTestConnection();
            String sql1="UPDATE user_table SET balance=balance-100 WHERE `user`=?";
            String sql2="UPDATE user_table SET balance=balance+100 WHERE `user`=?";
            //禁止自动提交
            testConnection.setAutoCommit(false);
            //修改数据(转账)
            DatabaseConnectivity.updateDataTransaction(testConnection, sql1, "AA");
            //模拟网络异常
//            System.out.println(1/0);
            DatabaseConnectivity.updateDataTransaction(testConnection, sql2, "BB");
            //提交
            testConnection.setAutoCommit(true);
            System.out.println("转账成功");
        } catch (Exception throwables) {
            throwables.printStackTrace();
            //回滚数据
            if (testConnection!=null){
                try {
                    //回滚数据
                    testConnection.rollback();
                    //恢复该连接对象的自动提交功能,针对于使用数据库连接池时
                    testConnection.setAutoCommit(true);
                    //关闭连接
                    testConnection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

        }

    }
}