Skip to content

Instantly share code, notes, and snippets.

@ashtewari
Last active August 29, 2015 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ashtewari/c93baa0235589050fd2a to your computer and use it in GitHub Desktop.
Save ashtewari/c93baa0235589050fd2a to your computer and use it in GitHub Desktop.
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