package com.hyc.study04;
import com.hyc.study02.utils.JDBCUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class TestTransaction {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = JDBCUtils.getConnection();
//关闭事务自动提交,自动开启事务
connection.setAutoCommit(false);
String sqlOut = "UPDATE `account` SET `money`=money-100 WHERE `id`=?";
preparedStatement = connection.prepareStatement(sqlOut);
preparedStatement.setInt(1,1);
preparedStatement.executeUpdate();
String sqlIn = "UPDATE `account` SET `money`=money+100 WHERE `id`=?";
preparedStatement = connection.prepareStatement(sqlIn);
preparedStatement.setInt(1,2);
preparedStatement.executeUpdate();
//业务操作完毕,提交事务
connection.commit();
} catch (SQLException throwables) {
try {
connection.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
throwables.printStackTrace();
}finally {
JDBCUtils.release(connection,preparedStatement,resultSet);
}
}
}
JDBC操作事务
最新推荐文章于 2024-10-17 11:21:39 发布