jdbc中的事务操作


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

//事务操作
public class JDBCdemo9 {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement preparedStatement1 = null;
        PreparedStatement preparedStatement2 = null;
        try {
            connection = JDBCUntils.getConnection();
            //开启事务
            connection.setAutoCommit(false);
            String sql1 = "update account set money = money - ? where name = ?";
            String sql2 = "update account set money = money + ? where name = ?";
            preparedStatement1 = connection.prepareStatement(sql1);
            preparedStatement2 = connection.prepareStatement(sql2);
            preparedStatement1.setInt(1,500);
            preparedStatement1.setString(2,"郭奉孝");
            preparedStatement2.setInt(1,500);
            preparedStatement2.setString(2,"曹操");
            preparedStatement1.executeUpdate();
//            int i = 3/0;
            preparedStatement2.executeUpdate();
            //提交事务
            connection.commit();
        } catch (Exception throwables) {
            try {
                if (connection != null){
                    //回滚事务
                    connection.rollback();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            throwables.printStackTrace();
        }finally {
            JDBCUntils.close(connection,preparedStatement1);
            if (preparedStatement2 != null){
                try {
                    preparedStatement2.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }
}


posted @ 2021-05-05 11:45  code-G  阅读(54)  评论(0编辑  收藏  举报