jdbc中事务的处理

/**
 * 模拟账户:Tom账户加钱+100,marry账户减钱-100
 * 开启事务
 */
public class jdbcTransaction {
    public static void main(String[] args) {
        // 不使用事务,进行账户的增加
        Connection connection = null;
        PreparedStatement preStatement = null;

        connection = JDBCUtils.getConnection();
        String reduce = "update account set money = money - ? where name = ?";
        String increase = "update account set money = money + ? where name = ?";
        Savepoint a = null;

        try {
            connection.setAutoCommit(false);
            preStatement = connection.prepareStatement(reduce);
            a = connection.setSavepoint("a");
            preStatement.setString(1,"100");
            preStatement.setString(2,"marry");
            int i = preStatement.executeUpdate();
            System.out.println("marry账户已经扣除了100元");

            i = i / 0;

            preStatement = connection.prepareStatement(increase);
            preStatement.setString(1,"100");
            preStatement.setString(1,"Tom");
            i = preStatement.executeUpdate();
            System.out.println("Tom已经增加了100元");


        } catch (SQLException e) {
            e.printStackTrace();
            try {
                connection.rollback(a);
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }finally {
            JDBCUtils.Close(null,preStatement,connection);
        }
    }
}

重点:

connection.setAutoCommit(false); //开启事务
a = connection.setSavepoint("a"); // 保存断点
connection.rollback(a); // 回滚断点

 

posted @ 2023-01-30 21:49  zwGitOne  阅读(76)  评论(0编辑  收藏  举报