JDBC事务

109 阅读1分钟

基本介绍

  1. JDBC程序中当一个Connection对象创建时,默认情况下是自动提交事务:每次执行一个sql 语句时,如果执行成功,就会向数据库自动提交,而不能回滚。
  2. JDBC程序中为了让多个sql语句作为一个整体执行,需要使用事务
  3. 调用Connection的setAutoCommit(false)可以取消自动提交事务
  4. 在所有sql语句都成功执行后,调用commit();方法提交事务
  5. 在其中某个操作失败或出现异常时,调用rollback();方法回滚事务
package com.csy.jdbc.utils;

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

public class transactionTest {
    public static void main(String[] args) {
        Connection connection = null;
        String sql = "update actor set phone = phone -100 where id = 1 ";
        String sql2 ="update actor set phone = phone + 100 where id = 2 ";
        PreparedStatement preparedStatement = null;
        try {
            connection = JDBCUtils.getConnection();
            //多条sql需要作为一个整体执行时(共同成功或失败)需要关闭自动提交,这样每条sql不会独立自动提交(这样是没有回滚的)。
            connection.setAutoCommit(false);
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.executeUpdate();

            preparedStatement = connection.prepareStatement(sql2);
            preparedStatement.executeUpdate();
            //关闭自动提交之后需要手动提交
            connection.commit();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JDBCUtils.close(null,preparedStatement,connection );
        }
    }
}