MST

星途 面试题库

面试题:Java JDBC中如何实现事务处理

请描述在Java JDBC中进行事务处理的步骤和关键代码。假设你有两个SQL语句,一个是插入数据到`users`表,另一个是更新`orders`表,要求这两个操作要么都成功,要么都失败。请用代码示例说明如何实现。
20.9万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试
  1. 事务处理步骤
    • 获取数据库连接。
    • 开启事务(通常通过设置自动提交为false)。
    • 执行多个数据库操作(SQL语句)。
    • 如果所有操作都成功,提交事务。
    • 如果有任何操作失败,回滚事务。
    • 关闭数据库连接。
  2. 关键代码
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class JdbcTransactionExample {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement insertStmt = null;
        PreparedStatement updateStmt = null;

        try {
            // 1. 获取数据库连接
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/yourdatabase", "username", "password");
            // 2. 开启事务
            connection.setAutoCommit(false);

            // 插入数据到users表
            String insertSql = "INSERT INTO users (username, email) VALUES (?,?)";
            insertStmt = connection.prepareStatement(insertSql);
            insertStmt.setString(1, "testUser");
            insertStmt.setString(2, "test@example.com");
            insertStmt.executeUpdate();

            // 更新orders表
            String updateSql = "UPDATE orders SET status =? WHERE order_id =?";
            updateStmt = connection.prepareStatement(updateSql);
            updateStmt.setString(1, "processed");
            updateStmt.setInt(2, 1);
            updateStmt.executeUpdate();

            // 3. 如果所有操作都成功,提交事务
            connection.commit();
            System.out.println("事务提交成功");
        } catch (SQLException e) {
            // 4. 如果有任何操作失败,回滚事务
            if (connection != null) {
                try {
                    connection.rollback();
                    System.out.println("事务回滚");
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
            e.printStackTrace();
        } finally {
            // 5. 关闭数据库连接
            if (insertStmt != null) {
                try {
                    insertStmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (updateStmt != null) {
                try {
                    updateStmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}