Interview question
How do you manage transactions in JDBC? JDBC में transactions कैसे manage करें?
Answer
Transactions group multiple SQL operations so they either all succeed (commit) or all fail together (rollback), preserving data consistency. JDBC connections are in auto-commit mode by default, which must be disabled to manage transactions manually.
Connection conn = null;
try {
conn = DriverManager.getConnection(url, user, password);
conn.setAutoCommit(false); // start manual transaction control
PreparedStatement debit = conn.prepareStatement(
'UPDATE accounts SET balance = balance - ? WHERE id = ?');
debit.setDouble(1, 100);
debit.setInt(2, fromAccountId);
debit.executeUpdate();
PreparedStatement credit = conn.prepareStatement(
'UPDATE accounts SET balance = balance + ? WHERE id = ?');
credit.setDouble(1, 100);
credit.setInt(2, toAccountId);
credit.executeUpdate();
conn.commit(); // both updates succeed together
System.out.println('Transfer successful');
} catch (SQLException e) {
if (conn != null) {
try {
conn.rollback(); // undo BOTH updates if anything failed
System.out.println('Transaction rolled back');
} catch (SQLException ex) {
ex.printStackTrace();
}
}
} finally {
if (conn != null) {
try {
conn.setAutoCommit(true); // restore default behavior
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
// Savepoints - partial rollback within a larger transaction
Savepoint savepoint = conn.setSavepoint('beforeRiskyOperation');
try {
// risky operation
} catch (SQLException e) {
conn.rollback(savepoint); // rolls back only to the savepoint, not the whole transaction
}Transactions कई SQL operations को group करते हैं ताकि या तो सब succeed (commit) हों या सब fail (rollback) हों, data consistency बनाए रखते हुए। JDBC connections default में auto-commit mode में होते हैं।
Connection conn = null;
try {
conn = DriverManager.getConnection(url, user, password);
conn.setAutoCommit(false); // manual transaction control
PreparedStatement debit = conn.prepareStatement(
'UPDATE accounts SET balance = balance - ? WHERE id = ?');
debit.setDouble(1, 100);
debit.setInt(2, fromAccountId);
debit.executeUpdate();
PreparedStatement credit = conn.prepareStatement(
'UPDATE accounts SET balance = balance + ? WHERE id = ?');
credit.setDouble(1, 100);
credit.setInt(2, toAccountId);
credit.executeUpdate();
conn.commit(); // दोनों updates साथ succeed
System.out.println('Transfer सफल');
} catch (SQLException e) {
if (conn != null) {
try {
conn.rollback(); // दोनों undo
System.out.println('Transaction rollback हुआ');
} catch (SQLException ex) {
ex.printStackTrace();
}
}
} finally {
if (conn != null) {
try {
conn.setAutoCommit(true);
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Savepoint savepoint = conn.setSavepoint('beforeRiskyOperation');
try {
// risky operation
} catch (SQLException e) {
conn.rollback(savepoint);
}Was this answer clear?