/ Published in: C#
Here is how I wrap database updates into a SQL transaction.
Expand |
Embed | Plain Text
DarthServerConnection.DataSource = "DarthServer"; DarthServerConnection.InitialCatalog = "DeathStarDB1"; DarthServerConnection.UserID = "tk421"; DarthServerConnection.Password = "tr00p3r"; { // The using statment will call dispose and close the connection. DeathStarDatabase.Open(); SqlTransaction SaveHeroes = DeathStarDatabase.BeginTransaction(); string ShutDownSql = "UPDATE GarbageDisposal SET Status = 'Shut Down'"; string OpenDoorSql = "UPDATE GarbageDisposal SET Door = 'Open' WHERE GarbageDisposalID = 3263827"; try { // Shut down the garbage disposal units on the detention level! No! Shut them all down! ShutDown.ExecuteNonQuery(); // We're alive. Open the door to 3263827. OpenDoor.ExecuteNonQuery(); SaveHeroes.Commit(); } catch ( Exception error ) { SaveHeroes.Rollback(); RescueEmail.Subject = "Error while Saving Heroes"; RescueEmail.Body = "An error has occured while attempting to save the following heroes:\n\r" + "Luke, Leia, Han, and Chewbacca.\n\r" + "The SQL statements that attempted to execute were:\n\r" + ShutDownSql + "\n\r" + OpenDoorSql + "\n\r" + "The error:\n\r" + error.ToString() + "\n\r" + "Result:\n\r" + "The heroes were not saved.\n\r" + "Action Item:\n\r" + "Please rescue R2D2 and C3PO from the Death Star."; YavinIVMail.Host = "mail.yaviniv.org"; YavinIVMail.Credentials = CredentialCache.DefaultNetworkCredentials; YavinIVMail.Send( RescueEmail ); } }
You need to login to post a comment.
