Update table using SqlDataAdapter

image_pdfimage_print
   


using System;
using System.Data;
using System.Data.SqlClient;

   class PropagateChanges {
      static void Main(){
         string connString = "server=(local)SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI";
         string qry = @"select * from employee ";
         string upd = @"update employee set firstname = @firstname where id = @id";

         SqlConnection conn = new SqlConnection(connString);

         try {
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = new SqlCommand(qry, conn);

            DataSet ds = new DataSet();   
            da.Fill(ds, "employee");

            DataTable dt = ds.Tables["employee"];

            dt.Rows[0]["firstname"] = "W";

            foreach (DataRow row in dt.Rows){
               Console.WriteLine(
                  "{0} {1}",
                  row["firstname"].ToString().PadRight(15),
                  row["lastname"].ToString().PadLeft(25));
            }

            // Update employees
            SqlCommand cmd = new SqlCommand(upd, conn);
            cmd.Parameters.Add("@firstname",SqlDbType.NVarChar,15, "firstname");
            SqlParameter parm = cmd.Parameters.Add("@id",SqlDbType.Int,4,"id");
            parm.SourceVersion = DataRowVersion.Original;
            da.UpdateCommand = cmd;
            da.Update(ds, "employee");
         } catch(Exception e) {
            Console.WriteLine("Error: " + e);
         } finally {
            conn.Close();
         }
      }  
   }


           
          


Use DataTable to update table in Database

image_pdfimage_print
   

using System;
using System.Data;
using System.Data.SqlClient;

   class PropagateAddsBuilder {
      static void Main() {
         string connString = "server=(local)SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI";
         string qry = @"select * from employee";
 
         SqlConnection conn = new SqlConnection(connString);

         try {
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = new SqlCommand(qry, conn);

            SqlCommandBuilder cb = new SqlCommandBuilder(da);

            DataSet ds = new DataSet();   
            da.Fill(ds, "employee");

            DataTable dt = ds.Tables["employee"];

            // Add a row
            DataRow newRow = dt.NewRow();
            newRow["firstname"] = "y";
            newRow["lastname"] = "y";
            dt.Rows.Add(newRow);

            foreach (DataRow row in dt.Rows){
               Console.WriteLine(
                  "{0} {1}",
                  row["firstname"].ToString().PadRight(15),
                  row["lastname"].ToString().PadLeft(25));
            }

            da.Update(ds, "employee");
         } catch(Exception e)  {
            Console.WriteLine("Error: " + e);
         } finally {
            conn.Close();
         }
      }  
   }



           
          


Update Data Using Transactions

image_pdfimage_print
   


/*
 * C# Programmers Pocket Consultant
 * Author: Gregory S. MacBeth
 * Email: gmacbeth@comporium.net
 * Create Date: June 27, 2003
 * Last Modified Date:
 * Version: 1
 */
using System;
using System.Data;
using System.Data.SqlClient;

namespace Client.Chapter_13___ADO.NET
{
    public class UpdatingDataUsingTransactions
    {
        static void Main(string[] args)
        {
            SqlConnection MyConnection = new SqlConnection(@"Data Source=(local); Initial Catalog = CaseManager; Integrated Security=true");

            MyConnection.Open();

            String MyString = "INSERT INTO Test(ID, Contact, Email)VALUES(1, 'Greg', 'Mac')";
            SqlTransaction MyTransaction = MyConnection.BeginTransaction();
            SqlCommand MyCmd = new SqlCommand(MyString, MyConnection, MyTransaction);

            MyCmd.ExecuteScalar();
            MyTransaction.Commit();
            MyConnection.Close();
        }
    }
}
           
          


Commit two delete sql command

image_pdfimage_print
   


using System;
using System.Data;
using System.Data.SqlClient;

   class SqlDemo {
      static void Main(){
         string connString = "server=(local)SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI";

         SqlConnection cn = new SqlConnection(connString);
         cn.Open();

         SqlTransaction objTrans = cn.BeginTransaction();

         try{
            SqlCommand cmd = cn.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.Transaction = objTrans;

            cmd.CommandText = "DELETE Employee WHERE Id = 222";
            cmd.ExecuteNonQuery();

            cmd.CommandText="DELETE Employee WHERE Id = 333";
            cmd.ExecuteNonQuery();

            objTrans.Commit();

            Console.WriteLine("Transaction Committed
");
         }
         catch (System.Data.SqlClient.SqlException  ex)
         {
            objTrans.Rollback();  

            Console.WriteLine("Error - TRANSACTION ROLLED BACK
" + ex.Message);
         }
         catch (System.Exception ex)
         {
            Console.WriteLine("System Error
" + ex.Message);
         }
         finally
         {
            cn.Close();  
         }
      }
   }

           
          


Transaction roll back and commit

image_pdfimage_print
   


using System;
using System.Data;
using System.Data.SqlClient;

   class SqlDemo {
      static void Main(){
         string connString = "server=(local)SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI";

         SqlConnection cn = new SqlConnection(connString);
         cn.Open();

         SqlTransaction objTrans = cn.BeginTransaction();

         try 
         {      
            SqlCommand cmd = cn.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.Transaction = objTrans;

            cmd.CommandText = "DELETE Employee WHERE Id = 222";
            cmd.ExecuteNonQuery();

            objTrans.Commit();
        
            Console.WriteLine("Transaction Committed
" );
         }
         catch (System.Data.SqlClient.SqlException ex)
         {
            objTrans.Rollback();
            Console.WriteLine("Error - TRANSACTION ROLLED BACK
" + ex.Message);
         }
         catch (System.Exception ex)
         {
            Console.WriteLine("System Error
" + ex.Message);
         }
         finally
         {
            cn.Close();
         }
      }
   }

           
          


illustrates the use of transactions

image_pdfimage_print
   

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy

Publisher: Sybex;
ISBN: 0782129110
*/

/*
  Example23_4.cs illustrates the use of transactions
*/

using System;
using System.Data;
using System.Data.SqlClient;

public class Example23_4
{

  public static void Main()
  {

    // formulate a string containing the details of the
    // database connection
    string connectionString =
      "server=localhost;database=Northwind;uid=sa;pwd=sa";

    // create a SqlConnection object to connect to the
    // database, passing the connection string to the constructor
    SqlConnection mySqlConnection =
      new SqlConnection(connectionString);

    // open the database connection using the
    // Open() method of the SqlConnection object
    mySqlConnection.Open();

    // step 1: create a SqlTransaction object and start the transaction
    // by calling the BeginTransaction() method of the SqlConnection
    // object
    SqlTransaction mySqlTransaction =
      mySqlConnection.BeginTransaction();

    // step 2: create a SqlCommand object to hold a SQL statement
    SqlCommand mySqlCommand = mySqlConnection.CreateCommand();

    // step 3: set the Transaction property for the SqlCommand object
    mySqlCommand.Transaction = mySqlTransaction;

    // step 4: formulate a string containing the first INSERT statement
    string insertString =
      "INSERT INTO Customers (" +
      "  CustomerID, CompanyName, ContactName, Address" +
      ") VALUES (" +
      "  'T2COM', 'T2 Company', 'Jason Price', '1 Main Street'" +
      ")";

    // step 5: set the CommandText property of the SqlCommand object to
    // the INSERT string
    mySqlCommand.CommandText = insertString;

    // step 6: run the first INSERT statement
    Console.WriteLine("Running first INSERT statement");
    mySqlCommand.ExecuteNonQuery();

    // step 7: formulate a second INSERT statement
    insertString =
      "INSERT INTO Orders (" +
      "  CustomerID" +
      ") VALUES (" +
      "  'T2COM'" +
      ")";

    // step 8: set the CommandText property of the SqlCommand object to
    // the second INSERT string
    mySqlCommand.CommandText = insertString;

    // step 9: run the second INSERT statement
    Console.WriteLine("Running second INSERT statement");
    mySqlCommand.ExecuteNonQuery();

    // step 10: commit the transaction using the Commit() method
    // of the SqlTransaction object
    Console.WriteLine("Committing transaction");
    mySqlTransaction.Commit();

    // close the database connection using the Close() method
    // of the SqlConnection object
    mySqlConnection.Close();

  }

}


           
          


Use of a transaction

image_pdfimage_print
   

using System;
using System.Data;
using System.Data.SqlClient;

class ExecuteTransaction
{
  public static void Main()
  {
    SqlConnection mySqlConnection =new SqlConnection("server=(local)SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI;");

    mySqlConnection.Open();

    SqlTransaction mySqlTransaction = mySqlConnection.BeginTransaction();

    SqlCommand mySqlCommand = mySqlConnection.CreateCommand();

    mySqlCommand.Transaction = mySqlTransaction;

    mySqlCommand.CommandText =
      "INSERT INTO Employee (" +
      "  ID, FirstName" +
      ") VALUES (" +
      "  10, 'Jason'" +
      ")";

    Console.WriteLine("Running first INSERT statement");
    mySqlCommand.ExecuteNonQuery();

    mySqlCommand.CommandText =
      "INSERT INTO Employee (" +
      "  ID, FirstName" +
      ") VALUES (" +
      "  11, 'Jason'" +
      ")";

    Console.WriteLine("Running second INSERT statement");
    mySqlCommand.ExecuteNonQuery();

    Console.WriteLine("Committing transaction");
    mySqlTransaction.Commit();

    mySqlConnection.Close();
  }
}