A SqlCommand object allows you to specify what type of interaction you want to perform with a data base.
A D V E R T I S E M E N T
For example, you can do select, insert, modify, and delete commands on rows of data in a data base 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. A later lesson on the SqlDataAdapter will explain how to implement an application that uses disconnected data. This lesson will also show you how to retrieve a single value from a data base, such as the number of records in a table.
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);
The line above is typical for instantiating a SqlCommand object. It takes a string parameter that holds the command you want to execute and a reference to a SqlConnection object. SqlCommand has a few overloads, which you will see in the examples of this tutorial.
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:
SqlCommand cmd = new SqlCommand("select CategoryName from Categories", conn);
SqlDataReader rdr = cmd.ExecuteReader();
Inserting Data
To insert data into a data base, use the ExecuteNonQuery method of the SqlCommand object. The following code shows how to insert data into a data base table:
string insertString = @"insert into Categories(CategoryName, Description)values('Miscellaneous',
'Whatever doesn''t fit elsewhere')";
SqlCommand cmd = new SqlCommand(insertString, conn);
cmd.ExecuteNonQuery();
Share And Enjoy:These icons link to social bookmarking sites where readers can share and discover new web pages.
Keywords:
The SqlCommand Object,asp net sqlcommand,vb net sqlcommand,ado net sqlcommand,sqlcommand stored procedure,asp net object,vb net object,visual basic net object,visual basic object,sqlcommand c#,sqlcommand net,sqlcommand dataset,sqlcommand executenonquery,sqlcommand executescalar,sqlcommand update,sqlcommand example