Deleting Data

image_pdfimage_print
   




using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Text;

class Program {
    static void Main(string[] args) {
        SqlConnection thisConnection = new SqlConnection(
             @"Server=(local)sqlexpress;Integrated Security=True;" +
             "Database=northwind");

        SqlDataAdapter thisAdapter = new SqlDataAdapter("SELECT CustomerID, CompanyName FROM Customers", thisConnection);
        SqlCommandBuilder thisBuilder = new SqlCommandBuilder(thisAdapter);
        DataSet thisDataSet = new DataSet();
        thisAdapter.Fill(thisDataSet, "Customers");

        Console.WriteLine("# rows before change: {0}",thisDataSet.Tables["Customers"].Rows.Count);
        DataColumn[] keys = new DataColumn[1];
        keys[0] = thisDataSet.Tables["Customers"].Columns["CustomerID"];
        thisDataSet.Tables["Customers"].PrimaryKey = keys;

        DataRow findRow = thisDataSet.Tables["Customers"].Rows.Find("ZACZI");

        if (findRow != null) {
            findRow.Delete();
            thisAdapter.Update(thisDataSet, "Customers");
        }

        Console.WriteLine("# rows after change: {0}",
             thisDataSet.Tables["Customers"].Rows.Count);
        thisConnection.Close();
    }
}


           
          


Deleting Data Using SQLStatements

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 DeletingDataUsingSQLStatements
    {
        static void Main(string[] args)
        {
            SqlConnection MyConnection = new SqlConnection(@"Data Source=(local); Initial Catalog = CaseManager; Integrated Security=true");

            MyConnection.Open();

            String MyString = "DELETE Test";
            SqlCommand MyCmd = new SqlCommand(MyString, MyConnection);

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



           
          


Deleting Data Using SqlCommandBuilder

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 DeletingDataUsingCommandBuilder
    {
        static void Main(string[] args)
        {
            SqlConnection MyConnection = new SqlConnection(@"Data Source=(local); Initial Catalog = CaseManager; Integrated Security=true");
            SqlDataAdapter MyDataAdapter = new SqlDataAdapter("SELECT * FROM Test", MyConnection);
            SqlCommandBuilder MyCmd = new SqlCommandBuilder(MyDataAdapter);
            DataSet MyDataSet = new DataSet();

            MyDataAdapter.Fill(MyDataSet);

            DataColumn[] MyKey = new DataColumn[1];

            MyKey[0] = MyDataSet.Tables[0].Columns[0];
            MyDataSet.Tables[0].PrimaryKey = MyKey;

            DataRow FindMyRow = MyDataSet.Tables[0].Rows.Find(1);

            FindMyRow.Delete();
            MyDataAdapter.Update(MyDataSet);
        }
    }
}



           
          


use the ExecuteNonQuery() method to run INSERT, UPDATE,and DELETE statements

image_pdfimage_print
   


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

class ExecuteInsertUpdateDelete
{
  public static void DisplayRow(SqlCommand mySqlCommand, string ID){
    mySqlCommand.CommandText ="SELECT ID, FirstName FROM Employee WHERE ID = '" + ID + "'";

    SqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();

    while (mySqlDataReader.Read())
    {
      Console.WriteLine("mySqlDataReader[" ID"] = " +
        mySqlDataReader["ID"]);
      Console.WriteLine("mySqlDataReader[" FirstName"] = " +
        mySqlDataReader["FirstName"]);
    }

    mySqlDataReader.Close();
  }

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

    SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
    mySqlCommand.CommandText ="INSERT INTO Employee (ID, FirstName) VALUES (" +
      "  9, 'Jason')";

    mySqlConnection.Open();

    int numberOfRows = mySqlCommand.ExecuteNonQuery();
    Console.WriteLine("Number of rows added = " + numberOfRows);
    DisplayRow(mySqlCommand, "9");

    mySqlCommand.CommandText = "UPDATE Employee SET FirstName = 'New' WHERE ID = '9'";

    numberOfRows = mySqlCommand.ExecuteNonQuery();
    Console.WriteLine("Number of rows updated = " + numberOfRows);
    DisplayRow(mySqlCommand, "9");

    mySqlCommand.CommandText ="DELETE FROM Employee WHERE ID = '9'";

    numberOfRows = mySqlCommand.ExecuteNonQuery();
    Console.WriteLine("Number of rows deleted = " + numberOfRows);

    mySqlConnection.Close();
  }
}


           
          


GetFactoryClasses, GetFactory

image_pdfimage_print
   
 


using System;
using System.Data;
using System.Data.Common;

class MainClass {
    public static void Main(string[] args) {
        using (DataTable providers = DbProviderFactories.GetFactoryClasses()) {
            foreach (DataRow prov in providers.Rows) {
                Console.WriteLine(" Name:{0}", prov["Name"]);
                Console.WriteLine("   Description:{0}", prov["Description"]);
                Console.WriteLine("   Invariant Name:{0}",prov["InvariantName"]);
            }
        }

        DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SqlClient");

        using (IDbConnection con = factory.CreateConnection()) {
            con.ConnectionString = @"Data Source = .sqlexpress;Database = Northwind; Integrated Security=SSPI";
            using (IDbCommand com = con.CreateCommand()) {
                com.CommandType = CommandType.StoredProcedure;
                com.CommandText = "Ten Most Expensive Products";
                con.Open();
                using (IDataReader reader = com.ExecuteReader()) {
                    Console.WriteLine(Environment.NewLine);
                    Console.WriteLine("Price of the Ten Most Expensive Products.");
                    while (reader.Read()) {
                        Console.WriteLine("  {0} = {1}", reader["TenMostExpensiveProducts"], reader["UnitPrice"]);
                    }
                }
            }
        }
    }
}

    


Create Connection

image_pdfimage_print
   
 


using System;
using System.Data;
using System.Data.Common;

class MainClass {
    public static void Main(string[] args) {
        DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SqlClient");

        using (IDbConnection con = factory.CreateConnection()) {
            con.ConnectionString = @"Data Source = .sqlexpress;Database = Northwind; Integrated Security=SSPI";
            using (IDbCommand com = con.CreateCommand()) {
                com.CommandType = CommandType.StoredProcedure;
                com.CommandText = "Ten Most Expensive Products";
                con.Open();
                using (IDataReader reader = com.ExecuteReader()) {
                    Console.WriteLine(Environment.NewLine);
                    Console.WriteLine("Price of the Ten Most Expensive Products.");
                    while (reader.Read()) {
                        Console.WriteLine("  {0} = {1}", reader["TenMostExpensiveProducts"], reader["UnitPrice"]);
                    }
                }
            }
        }
    }
}

    


Use DB2Connection class to connect to a DB2 database

image_pdfimage_print
   


using System;
using System.Data;
using IBM.Data.DB2;

class Db2Connect{
   static void Main() {
       string connString = @"database = sample;";

       DB2Connection conn = new DB2Connection(connString);

       try {
         conn.Open();
         Console.WriteLine("Connection opened.");

         // Display connection properties
         Console.WriteLine("Connection Properties:");   
         Console.WriteLine("	Connection String: {0}", conn.ConnectionString);    
         Console.WriteLine("	Database: {0}",conn.Database);   
         Console.WriteLine("	ServerVersion: {0}",conn.ServerVersion);
         Console.WriteLine("	State: {0}",conn.State);
      } catch (DB2Exception e) {
         Console.WriteLine("Error: " + e);  
      } finally  {
         conn.Close();
         Console.WriteLine("Connection closed.");
      }
   }
}