0% found this document useful (0 votes)
106 views

Lesson 03: The Sqlcommand Object: Sqlcommand CMD New Sqlcommand ("Select Categoryname From Categories", Conn)

The document discusses how to use the SqlCommand object in C# to perform queries, inserts, updates, and deletes on a SQL database. It shows how to instantiate a SqlCommand object, use the ExecuteReader method to perform queries and return result sets, use ExecuteNonQuery to perform inserts, updates, and deletes, and use ExecuteScalar to return a single value. It provides code examples for each operation and brings it all together in a single program that demonstrates reading, inserting, updating, and deleting data from a database table using the SqlCommand object.

Uploaded by

kravik2007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
106 views

Lesson 03: The Sqlcommand Object: Sqlcommand CMD New Sqlcommand ("Select Categoryname From Categories", Conn)

The document discusses how to use the SqlCommand object in C# to perform queries, inserts, updates, and deletes on a SQL database. It shows how to instantiate a SqlCommand object, use the ExecuteReader method to perform queries and return result sets, use ExecuteNonQuery to perform inserts, updates, and deletes, and use ExecuteScalar to return a single value. It provides code examples for each operation and brings it all together in a single program that demonstrates reading, inserting, updating, and deleting data from a database table using the SqlCommand object.

Uploaded by

kravik2007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 8

Lesson 03: The SqlCommand Object

Introduction
A SqlCommand object allows you to specify what type of interaction you want to
perform with a database.  For example, you can do select, insert, modify, and delete
commands on rows of data in a database table.  The SqlCommand object can be used to
support disconnected data management scenarios, but in this lesson we will only use the
SqlCommand object alone. 

Creating a SqlCommand Object


Similar to other C# objects, you instantiate a SqlCommand object via the new instance
declaration, as follows:

    SqlCommand cmd = new SqlCommand("select CategoryName from Categories",


conn);

Querying Data
When using a SQL select command, you retrieve a data set for viewing.  To accomplish
this with a SqlCommand object, you would use the ExecuteReader method, which returns
a SqlDataReader object.  We'll discuss the SqlDataReader in a future lesson.  The
example below shows how to use the SqlCommand object to obtain a SqlDataReader
object:

// 1. Instantiate a new command with a query and connection


SqlCommand cmd = new SqlCommand("select CategoryName from Categories", conn);

// 2. Call Execute reader to get query results


SqlDataReader rdr = cmd.ExecuteReader();
Inserting Data
To insert data into a database, use the ExecuteNonQuery method of the SqlCommand
object.  The following code shows how to insert data into a database table:

// prepare command string


 string insertString = @"
     insert into Categories
     (CategoryName, Description)
     values ('Miscellaneous', 'Whatever doesn''t fit elsewhere')";
 
 // 1. Instantiate a new command with a query and connection
 SqlCommand cmd = new SqlCommand(insertString, conn);
 
 // 2. Call ExecuteNonQuery to send command
 cmd.ExecuteNonQuery();

Notice the two apostrophes ('') in the insertString text for the word "doesn''t".  This is
how you escape the apostrophe to get the string to populate column properly. 

Another observation to make about the insert command is that we explicitly specified the
columns CategoryName and Description.  The Categories table has a primary key field
named CategoryID.  We left this out of the list because SQL Server will add this field
itself.  trying to add a value to a primary key field, such as CategoryID, will generate an
exception.

To execute this command, we simply call the ExecuteNonQuery method on the


SqlCommand instance, cmd.

Updating Data
The ExecuteNonQuery method is also used for updating data.  The following
code shows how to update data:

// prepare command string


 string updateString = @"
     update Categories
     set CategoryName = 'Other'
     where CategoryName = 'Miscellaneous'";
 
 // 1. Instantiate a new command with command text only
 SqlCommand cmd = new SqlCommand(updateString);
 
 // 2. Set the Connection property
 cmd.Connection = conn;
 
 // 3. Call ExecuteNonQuery to send command
 cmd.ExecuteNonQuery();

The ExecuteNonQuery method performs the update command.


Deleting Data
You can also delete data using the ExecuteNonQuery method.  The following
example shows how to delete a record from a database with the
ExecuteNonQuery method:

// prepare command string


 string deleteString = @"
     delete from Categories
     where CategoryName = 'Other'";
 
 // 1. Instantiate a new command
 SqlCommand cmd = new SqlCommand();
 
 // 2. Set the CommandText property
 cmd.CommandText = deleteString;
 
 // 3. Set the Connection property
 cmd.Connection = conn;
 
 // 4. Call ExecuteNonQuery to send command
 cmd.ExecuteNonQuery();

This example uses the SqlCommand constructor with no parameters.  Instead, it explicity
sets the CommandText and Connection properties of the SqlCommand object, cmd. 

Getting Single values


Sometimes all you need from a database is a single value, which could be a count, sum,
average, or other aggregated value from a data set.  Performing an ExecuteReader and
calculating the result in your code is not the most efficient way to do this.  The best
choice is to let the database perform the work and return just the single value you need. 
The following example shows how to do this with the ExecuteScalar method:

// 1. Instantiate a new command


 SqlCommand cmd = new SqlCommand("select count(*) from Categories", conn);
 
 // 2. Call ExecuteNonQuery to send command
 int count = (int)cmd.ExecuteScalar();

The query in the SqlCommand constructor obtains the count of all records from the
Categories table.  This query will only return a single value.  The ExecuteScalar method
in step 2 returns this value.  Since the return type of ExecuteScalar is type object, we use
a cast operator to convert the value to int.
This code is part of the GetNumberOfRecords method of Listing 1 in the Putting it All
Together section later in this lesson.
Putting it All Together
For simplicity, we showed snippets of code in previous sections to demonstrate the
applicable techniques .  It is also useful to have an entire code listing to see how this code
is used in a working program.  Listing 1 shows all of the code used in this example, along
with a driver in the Main method to produce formatted output.

Listing 1.  SqlConnection Demo

 using System;
 using System.Data;
 using System.Data.SqlClient;
 
 /// <summary>
 /// Demonstrates how to work with SqlCommand objects
 /// </summary>
 class SqlCommandDemo
 {
     SqlConnection conn;
 
     public SqlCommandDemo()
     {
         // Instantiate the connection
         conn = new SqlConnection(
            "Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI");
     }
 
     // call methods that demo SqlCommand capabilities
     static void Main()
     {
         SqlCommandDemo scd = new SqlCommandDemo();
 
         Console.WriteLine();
         Console.WriteLine("Categories Before Insert");
         Console.WriteLine("------------------------");
 
         // use ExecuteReader method
         scd.ReadData();
 
         // use ExecuteNonQuery method for Insert
         scd.Insertdata();
         Console.WriteLine();
         Console.WriteLine("Categories After Insert");
         Console.WriteLine("------------------------------");
 
        scd.ReadData();
 
         // use ExecuteNonQuery method for Update
         scd.UpdateData();
 
         Console.WriteLine();
         Console.WriteLine("Categories After Update");
         Console.WriteLine("------------------------------");
 
         scd.ReadData();
 
         // use ExecuteNonQuery method for Delete
         scd.DeleteData();
 
         Console.WriteLine();
         Console.WriteLine("Categories After Delete");
         Console.WriteLine("------------------------------");
 
         scd.ReadData();
 
         // use ExecuteScalar method
         int numberOfRecords = scd.GetNumberOfRecords();
 
         Console.WriteLine();
         Console.WriteLine("Number of Records: {0}", numberOfRecords);
     }
 
     /// <summary>
     /// use ExecuteReader method
     /// </summary>
     public void ReadData()
     {
        SqlDataReader rdr = null;
 
         try
         {
             // Open the connection
             conn.Open();
 
             // 1. Instantiate a new command with a query and connection
             SqlCommand cmd = new SqlCommand("select CategoryName from Categories", conn);
 
             // 2. Call Execute reader to get query results
             rdr = cmd.ExecuteReader();
 
             // print the CategoryName of each record
             while (rdr.Read())
             {
                 Console.WriteLine(rdr[0]);
             }
         }
         finally
         {
             // close the reader
             if (rdr != null)
             {
                 rdr.Close();
             }
 
             // Close the connection
             if (conn != null)
             {
                 conn.Close();
             }
         }
     }
 
     /// <summary>
     /// use ExecuteNonQuery method for Insert
     /// </summary>
     public void Insertdata()
     {
         try
         {
             // Open the connection
             conn.Open();
 
             // prepare command string
             string insertString = @"
                 insert into Categories
                 (CategoryName, Description)
                 values ('Miscellaneous', 'Whatever doesn''t fit elsewhere')";
 
             // 1. Instantiate a new command with a query and connection
             SqlCommand cmd = new SqlCommand(insertString, conn);
 
             // 2. Call ExecuteNonQuery to send command
             cmd.ExecuteNonQuery();
         }
         finally
         {
             // Close the connection
             if (conn != null)
             {
                 conn.Close();
             }
         }
     }
 
     /// <summary>
     /// use ExecuteNonQuery method for Update
     /// </summary>
     public void UpdateData()
     {
         try
         {
             // Open the connection
             conn.Open();
 
             // prepare command string
             string updateString = @"
                 update Categories
                 set CategoryName = 'Other'
                 where CategoryName = 'Miscellaneous'";
 
             // 1. Instantiate a new command with command text only
             SqlCommand cmd = new SqlCommand(updateString);
 
             // 2. Set the Connection property
             cmd.Connection = conn;
 
             // 3. Call ExecuteNonQuery to send command
             cmd.ExecuteNonQuery();
        }
         finally
         {
             // Close the connection
             if (conn != null)
             {
                 conn.Close();
             }
         }
     }
 
     /// <summary>
     /// use ExecuteNonQuery method for Delete
     /// </summary>
     public void DeleteData()
     {
         try
         {
             // Open the connection
             conn.Open();
 
             // prepare command string
             string deleteString = @"
                 delete from Categories
                 where CategoryName = 'Other'";
 
             // 1. Instantiate a new command
             SqlCommand cmd = new SqlCommand();
 
             // 2. Set the CommandText property
             cmd.CommandText = deleteString;
 
             // 3. Set the Connection property
             cmd.Connection = conn;
 
             // 4. Call ExecuteNonQuery to send command
             cmd.ExecuteNonQuery();
         }
         finally
         {
             // Close the connection
             if (conn != null)
             {
                 conn.Close();
             }
         }
     }
 
     /// <summary>
     /// use ExecuteScalar method
     /// </summary>
     /// <returns>number of records</returns>
     public int GetNumberOfRecords()
     {
         int count = -1;
 
         try
         {
             // Open the connection
             conn.Open();
 
             // 1. Instantiate a new command
             SqlCommand cmd = new SqlCommand("select count(*) from Categories", conn);
 
             // 2. Call ExecuteScalar to send command
             count = (int)cmd.ExecuteScalar();
         }
         finally
         {
            // Close the connection
             if (conn != null)
             {
                 conn.Close();
             }
         }
         return count;
     }
 }

You might also like