Jdbc操作事务(提交、回滚)----以银行转账为例

以银行转账为例----Jdbc操作事务(提交、回滚)

private Statement statement;
private Connection conn;

@Test
public void test01() throws Exception {
    Class.forName("com.mysql.jdbc.Driver");
    conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db2", "root", "root");
    statement = conn.createStatement();
    zz(500, "xiaoming", "xiaohua");
    statement.close();
    conn.close();
}


public void zz(Integer money, String from, String to) throws Exception {
    conn.setAutoCommit(false);//开启事务
    ResultSet resultSet = statement.executeQuery("select balance from account WHERE name='" + from + "'");
    if (resultSet.next()) {
        int balance = resultSet.getInt("balance");
        if (balance >= money) {
            statement.execute("update account set balance=balance-" + money + " where name='" + from + "'");
            statement.execute("update account set balance=balance+" + money + " where name='" + to + "'");
        } else {
            conn.rollback();//回滚
            System.out.println("转账失败....");
        }
    }
    conn.commit();//提交事务
}

猜你喜欢

转载自blog.csdn.net/Chenlele710147/article/details/84800628