Which JDBC method is used to commit a transaction?

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

a) commitTransaction()
b) executeCommit()
c) commit()
d) finalizeTransaction()

Answer:

c) commit()

Explanation:

The commit() method is used to commit a transaction in JDBC. When auto-commit mode is disabled, multiple SQL statements can be grouped into a single transaction. After executing all the statements, calling commit() on the Connection object makes the changes permanent in the database.

Here’s an example of using commit():

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();

In this example, two SQL update statements are executed as part of a transaction. The commit() method is called to save the changes to the database.

Using commit() allows for greater control over transactions, enabling you to ensure data consistency and integrity in complex operations.

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