How to manually rollback a transaction in Java?

In Java, we can manually roll back a transaction using the Connection object in JDBC. Here is a simple example:

Connection conn = null;
try {
    conn = DriverManager.getConnection(url, username, password);

    conn.setAutoCommit(false); // 关闭自动提交

    // 执行一系列数据库操作

    conn.commit(); // 提交事务
} catch (SQLException e) {
    if (conn != null) {
        try {
            conn.rollback(); // 回滚事务
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
    e.printStackTrace();
} finally {
    if (conn != null) {
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

In this example, we first obtain a database connection using DriverManager.getConnection() method and set conn.setAutoCommit(false) to disable auto commit. Then, after performing a series of database operations, if an exception occurs, we can manually rollback the transaction by calling conn.rollback() in the catch block. Finally, we close the connection in the finally block.

This way enables manually rolling back transactions in Java.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds