Which method is used to rollback a transaction in JDBC?

Java MCQ: Which method is used to rollback a transaction in JDBC?

a) undoTransaction()
b) rollbackTransaction()
c) rollback()
d) revert()

Answer:

c) rollback()

Explanation:

The rollback() method is used to rollback a transaction in JDBC. When auto-commit mode is disabled, you can use rollback() on the Connection object to undo all changes made in the current transaction. This is useful in situations where an error occurs during a transaction, and you need to revert the database to its previous state.

Here’s an example of using rollback():

try {
    conn.setAutoCommit(false);
    stmt.executeUpdate("UPDATE accounts SET balance = balance - 100 WHERE id = 1");
    stmt.executeUpdate("UPDATE accounts SET balance = balance + 100 WHERE id = 2");
    conn.commit();
} catch (SQLException e) {
    conn.rollback();  // Rollback the transaction if an error occurs
}

In this example, if an exception occurs while executing the SQL statements, the rollback() method is called to revert the database to its previous state before the transaction began.

The rollback() method is crucial for maintaining data integrity and ensuring that only successful transactions are committed to the database.

Reference links:

https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html

Leave a Comment

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

Scroll to Top