MST
星途 面试题库

面试题:Java JDBC中事务管理的基本操作

在Java JDBC中,如何开启、提交和回滚一个事务?请写出相应的代码示例。
47.6万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试

以下是在Java JDBC中开启、提交和回滚事务的代码示例:

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

public class TransactionExample {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement preparedStatement1 = null;
        PreparedStatement preparedStatement2 = null;

        try {
            // 数据库连接
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/yourdatabase", "username", "password");
            // 开启事务(默认自动提交,关闭自动提交即开启事务)
            connection.setAutoCommit(false); 

            // 第一个SQL操作
            String sql1 = "INSERT INTO your_table (column1, column2) VALUES (?,?)";
            preparedStatement1 = connection.prepareStatement(sql1);
            preparedStatement1.setString(1, "value1");
            preparedStatement1.setString(2, "value2");
            preparedStatement1.executeUpdate();

            // 第二个SQL操作
            String sql2 = "UPDATE your_table SET column2 =? WHERE column1 =?";
            preparedStatement2 = connection.prepareStatement(sql2);
            preparedStatement2.setString(1, "newValue2");
            preparedStatement2.setString(2, "value1");
            preparedStatement2.executeUpdate();

            // 提交事务
            connection.commit(); 
            System.out.println("事务提交成功");
        } catch (SQLException e) {
            // 回滚事务
            if (connection != null) {
                try {
                    connection.rollback();
                    System.out.println("事务回滚");
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (preparedStatement2 != null) {
                try {
                    preparedStatement2.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (preparedStatement1 != null) {
                try {
                    preparedStatement1.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
  1. 开启事务:通过调用Connection对象的setAutoCommit(false)方法关闭自动提交,从而开启事务。
  2. 提交事务:在一系列数据库操作成功完成后,调用Connection对象的commit()方法提交事务,将所有操作永久保存到数据库。
  3. 回滚事务:如果在执行数据库操作过程中发生异常,调用Connection对象的rollback()方法回滚事务,撤销所有未提交的操作。