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.