Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
private static void ExecuteSqlTransaction(string connectionString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = connection.CreateCommand();
SqlTransaction transaction;
// Start a ransaction.
transaction = connection.BeginTransaction("MyTransaction");
command.Connection = connection;
command.Transaction = transaction;
try
{
command.CommandText = "Insert into MyTable(ColumnA, ColumnB) VALUES (1234, 'ValueB')";
command.ExecuteNonQuery();
command.CommandText = "Insert into MyTable(ColumnA, ColumnB) VALUES (5678, 'Another Value')";
command.ExecuteNonQuery();
// Attempt to commit the transaction.
transaction.Commit();
Console.WriteLine("Both records are written to database.");
}
catch (Exception ex)
{
// Log exception
// Attempt to roll back the transaction. 
try
{
transaction.Rollback();
}
catch (Exception exception)
{
// This catch block will handle any errors that may have occurred 
// on the server that would cause the rollback to fail.
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment