Mid From PDF ADO.NET ADO.NET

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

  1. Define — one clear sentence (the short answer above).
  2. Example — relate it to a project like ShopNest or your real work.
  3. Trade-off — when you would not use it.
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details