Junior — Middle
Can you explain how the transaction rollback operation works?
sobes.tech AI
Answer from AI
A transaction rollback is used to cancel all changes made within the current transaction if an error occurs or the operation cannot be completed successfully. In Java, for example, when working with a database via JDBC, a transaction begins by disabling auto-commit (connection.setAutoCommit(false)), then SQL queries are executed. If everything goes well, connection.commit() is called to save the changes. If an error occurs, connection.rollback() is called to revert the database to its state before the transaction started.
This guarantees data integrity and prevents partially completed operations.
Example in Java with JDBC:
Connection connection = dataSource.getConnection();
try {
connection.setAutoCommit(false);
// Execute multiple database operations
// ...
connection.commit();
} catch (SQLException e) {
connection.rollback(); // Rollback all changes
} finally {
connection.setAutoCommit(true);
connection.close();
}