Database Reference
In-Depth Information
C H A P T E R 13
Executing ADO.NET Commands to
Retrieve Data
Once you've established a connection to the database, you want to start interacting with it and getting it
doing something useful for you. You may need to retrieve, add, update, or delete some data, or perhaps
modify the database in some other way, usually by running a query. Whatever the task, it will inevitably
involve a command.
In this chapter, we'll explain commands, which are objects that encapsulate the T-SQL for the
action you want to perform and that provide methods for submitting it to the database. Each data
provider has a command class that implements the System.Data.IDbCommand interface.
In this chapter, we'll cover the following:
Creating commands
Executing commands
Executing commands with multiple results
Executing statements
Using stored procedures
We'll use the SQL Server data provider ( System.Data.SqlClient ) in our examples. Its command is
named SqlCommand . The commands for the other data providers work the same way.
Creating a Command
For your commands to be executed against a database, each command must be associated with a
connection to the database. You do this by setting the Connection property of the command, and in
order to save resources, multiple commands can use the same connection. You can create a command
by using the SqlCommand constructor. Once a command is created, then it's ready to execute the SQL
statements you associated with an established connection. You will see command execution in
statements in the following section.
Assigning Text to a Command
Every command has a property, CommandText , that holds the SQL statement that your created command
object will execute. You can assign to this property directly or specify it when constructing the
command. Let's look at these alternatives.
 
Search WWH ::




Custom Search