Last active
August 29, 2015 14:20
-
-
Save ashtewari/c93baa0235589050fd2a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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