Junior — Middle
Is it possible to execute multiple different SQL queries within a single transaction?
sobes.tech AI
Answer from AI
Yes, multiple different SQL queries can be executed within a single transaction. A transaction ensures atomicity, meaning all queries inside it either succeed together or are rolled back in case of an error. In Java, using JDBC, this is done as follows:
connection.setAutoCommit(false); // disable auto-commit
try {
Statement stmt = connection.createStatement();
stmt.executeUpdate("INSERT INTO users (name) VALUES ('Alice')");
stmt.executeUpdate("UPDATE accounts SET balance = balance - 100 WHERE user_id = 1");
connection.commit(); // confirm the transaction
} catch (SQLException e) {
connection.rollback(); // rollback on error
}