Home
Browse all 647 examples
Download all 647 examples
Download sample chapters
Reviews
Errata
Acknowledgments
Links on .NET
Paradoxal Press

Buy directly from Paradoxal Press at $33.99 (Save 43%)



Category: Programming
Level: Beginner to seasoned
900 pages
ISBN-10 097661322-0
ISBN-13 978-097661322-0
$59.99 USA
$79.99 CANADA


Listing 20-1 extracted from chapter Transactions


Listing 19-24<     > Listing 20-2


This listing can be compiled with the command line:
csc.exe /target:exe Example_20_1.cs
Errors: 0 Warnings: 0


Example_20_1.cs
using System.Data.Common;
using System.Data.SqlClient;
class Program {
   static void Main() {
      string sCnx =
         "server = localhost ; uid=sa ; pwd =; database = ORGANIZATION";
      string sCmd1 =
         "INSERT INTO DEPARTEMENTS VALUES ('COM','Communication')";
      string sCmd2 =
    "INSERT INTO EMPLOYEES VALUES ('COM','Smith','Adam','(123) 456-7899')";
      try {
         using (SqlConnection cnx = new SqlConnection(sCnx)) {
            cnx.Open();
            DbTransaction tx = cnx.BeginTransaction();
            DbCommand cmd = new SqlCommand(sCmd1, cnx);
            cmd.Transaction = tx;
            cmd.ExecuteNonQuery();
            cmd.CommandText = sCmd2;
            cmd.ExecuteNonQuery();
            tx.Commit();
            // Here, both commands have been successfully executed.
            // and the transaction is done.
         // end using cnx.
      catch {
         // If an exception has been raised before or during the
         // call to 'Commit()' data of the DB haven't been updated.
      }
   }
}	
Copyright Patrick Smacchia 2006 2007