Commit or rollback the transaction based on the outcome.?
Short answer: Example: SqlConnection connection = new SqlConnection(connectionString); connection.Open(); SqlTransaction transaction = connection.BeginTransaction(); try { SqlCommand command1 = new SqlCommand("UPDATE Customers SET Balance = Balance - 100", connection, transaction); SqlCommand command2 = new SqlCommand("UPDATE Accounts SET Balance = Balance + 100", connection, transaction); command1.ExecuteNonQuery();…
Explain a bit more
command2.ExecuteNonQuery(); transaction.Commit(); // Commit the transaction } catch (Exception) { transaction.Rollback(); // Rollback if there is an error } finally { connection.Close(); }
Example code
SqlConnection connection = new SqlConnection(connectionString); connection.Open(); SqlTransaction transaction = connection.BeginTransaction(); try { SqlCommand command1 = new SqlCommand("UPDATE Customers SET Balance = Balance - 100", connection, transaction); SqlCommand command2 = new SqlCommand("UPDATE Accounts SET Balance = Balance + 100", connection, transaction); command1.ExecuteNonQuery(); command2.ExecuteNonQuery(); transaction.Commit(); // Commit the transaction } catch (Exception) { transaction.Rollback(); // Rollback if there is an error } finally { connection.Close(); }
Real-world example (ShopNest)
Placing an order updates stock and inserts the order row in one SqlTransaction—either both succeed or both roll back.
Say this in the interview
- Define — one clear sentence (the short answer above).
- Example — relate it to a project like ShopNest or your real work.
- Trade-off — when you would not use it.
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png