本文档由李欣蔚(nirvana_li)翻译自http://www.csharp-station.com/,转载请注名出处!
更新日期2006-2-14
Lesson 03: The SqlCommand Object
SqlCommand对象
This lesson describes the SqlCommand object and how you use it to interact with a data base. Here are the objectives of this lesson:
这节课描述了SqlCommand对象以及如何使用它与数据库交互。下面是本课的目标:
Know what a command object is.
Learn how to use the ExecuteReader method to query data.
Learn how to use the ExecuteNonQuery method to insert and delete data.
Learn how to use the ExecuteScalar method to return a single value.
知道什么是command对象
学习如何使用ExecuteReader方法查询数据
学习如何使用ExecuteNonQuery方法插入和删除对象
学习如何使用EXecuteScalar方法返回单一值
Introduction
介绍
A SqlCommand object allows you to specify what type of interaction you want to perform with a data base. 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.
SqlCommand对象允许你指定在数据库上执行的操作的类型。比如,你能够对数据库中的行数据执行select,insert,modify以及delete命令。SqlCommand对象能被用来支持断开连接数据管理的情况,但是在这节课我们将只单独使用SqlCommand对象。后面关于SqlDataAdapter的课程将解释如何使用断开数据实现应用程序。这节课将同时展示如何从数据库中返回一个单独的值,比如表中记录的数量。
Creating a SqlCommand Object
创建SqlCommand对象
Similar to other C# objects, you instantiate a SqlCommand object via the new instance declaration, as follows:
与其他C#对象相似,通过new实例声明来实例化SqlCommand对象:
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.
上面一行是典型的实例化SqlCommand对象的代码。它使用一个string参数来保存你想要执行的命令以及一个关于SqlConnection对象的引用。SqlCommand具有重载形式,这些形式你将在以后的示例中看到。
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:
当使用SQL的select命令,会得到一组数据集。为了和SqlCommand对象配合使用,你应该使用ExecuteReader方法,它返回一个SqlDataReader对象。我们将在后面的内容讨论SqlDataReader。下面的例子显示了如何使用SqlCommand对象来得到SqlDataReader对象:
// 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();
In the example above, we instantiate a SqlCommand object, passing the command string and connection object to the constructor. Then we obtain a SqlDataReader object by calling the ExecuteReader method of the SqlCommand object, cmd.
在上面的示例中,我们通过传递命令字符串核连接对象到构造函数的方式实体化了SqlCommand对象。然后我们通过SqlCommand对象cmd调用ExecuteReader方法得到了SqlDataReader对象。
This code is part of the ReadData method of Listing 1 in the Putting it All Together section later in this lesson.
这些代码是表1中ReadData方法的一部分,我们将在后面集中介绍。
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:
要对数据库插入数据,使用SqlCommand对象的ExecuteNonQuery方法。下面的代码显示了如何向数据库表插入数据:
// 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();
The SqlCommand instantiation is just a little different from what you've seen before, but it is basically the same. Instead of a literal string as the first parameter of the SqlCommand constructor, we are using a variable, insertString. The insertString variable is declared just above the SqlCommand declaration.
SqlCommand的实例化过程与以前看到的有一些区别,但是基本一致。在构造函数的第一个字符串参数中是用的是插入字符串变量而不三字符串字面值。该变量在SqlCommand声明之前被声明了。
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.
注意在insertString文本中“doesn’’t”的两个单引号(’’)。这是将它转义为适当的单引号。
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.
另外一个需要注意的是我们显式指明了列:CategoryName和Description。列表中有一个主键名为CategoryID。我们忽略这列因为SQL Server将自动添加此字段。试图对主键比如CategoryID添加值会产生异常。
To execute this command, we simply call the ExecuteNonQuery method on the SqlCommand instance, cmd.
为了执行此命令,我们简单的对SqlCommand实体cmd调用ExecuteNonQuery方法。
This code is part of the InsertData method of Listing 1 in the Putting it All Together section later in this lesson.
这段代码是表1中InsertData方法的一部分,我们将在后面集中介绍。
Updating Data
更新数据
The ExecuteNonQuery method is also used for updating data. The following code shows how to update data:
ExecuteNonQuery方法同样用来更新数据。下面的代码显示了如何更新数据:
// 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();
Again, we put the SQL command into a string variable, but this time we used a different SqlCommand constructor that takes only the command. In step 2, we assign the SqlConnection object, conn, to the Connection property of the SqlCommand object, cmd.
再一次,我们将SQL命令赋给字符串变量,但是这次我们使用了不同的SqlCommand构造函数,它只适用了命令。在第2步,将SqlConnection对象conn赋值给SqlCommand对象cmd的连接属性。
This could have been done with the same constructor used for the insert command, with two parameters. It demonstrates that you can change the connection object assigned to a command at any time.
这同样能够用上面insert命令中使用两个参数的构造函数实现。它说明了你能够在任何时候改变赋值给命令对象的连接对象。
The ExecuteNonQuery method performs the update command.
ExecuteNonQuery方法执行更新命令。
This code is part of the UpdateData method of Listing 1 in the Putting it All Together section later in this lesson.
这些代码是表1UpdateData方法的一部分。我们将在本课后面集中介绍。
Deleting Data
删除数据
You can also delete data using the ExecuteNonQuery method. The following example shows how to delete a record from a data base with the ExecuteNonQuery method:
你同样能够使用ExecuteNonQuery方法删除数据。下面的例子说明了如何使用EXecuteNonQuery方法删除数据库中的记录。
// 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.
这个示例使用了没有参数的SqlCommand构造函数。取而代之的是显式地设置了CommandText和SqlCommand对象的连接属性。
We could have also used either of the two previous SqlCommand constructor overloads, used for the insert or update command, with the same result. This demonstrates that you can change both the command text and the connection object at any time.
我们同样能够使用SqlCommand构造函数在前面的两个重载形式——用来插入或者更新命令——得到相同的结果。它说明了在任何时候既能够改变命令文本又能够改变连接对象。
The ExecuteNonQuery method call sends the command to the data base.
ExecuteNonQuery方法调用将命令传递给数据库。
This code is part of the DeleteData method of Listing 1 in the Putting it All Together section later in this lesson.
这些代码是表1中DeleteData方法的一部分。我们将在后面的内容中集中介绍。

