Tải bản đầy đủ (.pdf) (8 trang)

Executing Commands that Modify Information in the Database

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (26.09 KB, 8 trang )


Executing Commands that Modify Information in the Database
You can use the ExecuteNonQuery() method of a Command object to execute any
command that doesn't return a result set from the database. In this section, you'll learn
how to use the ExecuteNonQuery() method to execute commands that modify
information in the database.
You can use the ExecuteNonQuery() method to execute SQL INSERT, UPDATE, and
DELETE statements. You can also use the ExecuteNonQuery() method to call stored
procedures that don't return a value, or issue Data Definition Language (DDL) statements
such as CREATE TABLE and CREATE INDEX. (DDL was covered in Chapter 3
,
"Introduction to the Structured Query Language.") Table 8.8
summarizes the
ExecuteNonQuery() method.
Table 8.8: THE ExecuteNonQuery() METHOD
METHOD RETURN
TYPE
DESCRIPTION
ExecuteNonQuery() int Used to execute SQL statements that don't return a
result set, such as INSERT, UPDATE, and DELETE
statements, DDL statements, or stored procedure calls
that don't return a result set. The int value returned is
the number of database rows affected by the command,
if any.
You'll learn how to execute INSERT, UPDATE, and DELETE statements, and how to
execute DDL statements in this section. You'll learn how to execute stored procedure
calls later in the "Executing SQL Server Stored Procedures
" section.
Executing INSERT, UPDATE, and DELETE Statements Using the
ExecuteNonQuery() Method
Let's take a look at an example that executes an INSERT statement using the


ExecuteNonQuery() method. First, a Command object is needed:
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
Next, you set the CommandText property of your Command object to the INSERT
statement. The following example sets the CommandText property of mySqlCommand to
an INSERT statement that adds a row to the Customers table:
mySqlCommand.CommandText =
"INSERT INTO Customers (" +
" CustomerID, CompanyName" +
") VALUES (" +
" 'J2COM', 'Jason Price Corporation'" +
")";
Finally, you execute the INSERT statement using the ExecuteNonQuery() method:
int numberOfRows = mySqlCommand.ExecuteNonQuery();

The ExecuteNonQuery() method returns an int value that indicates the number of rows
affected by the command. In this example, the value returned is the number of rows
added to the Customers table, which is 1 since one row was added by the INSERT
statement.
Let's take a look at an example that executes an UPDATE statement to modify the new
row just added. The following code sets the CommandText property of mySqlCommand
to an UPDATE statement that modifies the CompanyName column of the new row, and
then calls the ExecuteNonQuery() method to execute the UPDATE:
mySqlCommand.CommandText =
"UPDATE Customers " +
"SET CompanyName = 'New Company' " +
"WHERE CustomerID = 'J2COM'";
numberOfRows = mySqlCommand.ExecuteNonQuery();
The ExecuteNonQuery() method returns the number of rows modified by the UPDATE
statement, which is 1 since one row was modified.
Finally, let's take a look at an example that executes a DELETE statement to remove the

new row:
mySqlCommand.CommandText =
"DELETE FROM Customers " +
"WHERE CustomerID = 'J2COM'";
numberOfRows = mySqlCommand.ExecuteNonQuery();
ExecuteNonQuery() returns 1 again because only one row was removed by the DELETE
statement.
Listing 8.7
illustrates the use of the ExecuteNonQuery() method to execute the INSERT,
UPDATE, and DELETE statements shown in this section. This program features a
procedure named DisplayRow() that retrieves and displays the details of a specified row
from the Customers table. DisplayRow() is used in the program to show the result of the
INSERT and UPDATE statements.
Listing 8.7: EXECUTEINSERTUPDATEDELETE.CS

/*
ExecuteInsertUpdateDelete.cs illustrates how to use the
ExecuteNonQuery() method to run INSERT, UPDATE,
and DELETE statements
*/

using System;
using System.Data;
using System.Data.SqlClient;

class ExecuteInsertUpdateDelete
{
public static void DisplayRow(
SqlCommand mySqlCommand, string CustomerID
)

{
mySqlCommand.CommandText =
"SELECT CustomerID, CompanyName " +
"FROM Customers " +
"WHERE CustomerID = '" + CustomerID + "'";

SqlDataReader mySqlDataReader =
mySqlCommand.ExecuteReader();

while (mySqlDataReader.Read())
{
Console.WriteLine("mySqlDataReader[\" CustomerID\"] = " +
mySqlDataReader["CustomerID"]);
Console.WriteLine("mySqlDataReader[\" CompanyName\"] = " +
mySqlDataReader["CompanyName"]);
}

mySqlDataReader.Close();
}

public static void Main()
{
SqlConnection mySqlConnection =
new SqlConnection(
"server=localhost;database=Northwind;uid=sa;pwd=sa"
);

// create a SqlCommand object and set its Commandtext property
// to an INSERT statement
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();

mySqlCommand.CommandText =
"INSERT INTO Customers (" +
" CustomerID, CompanyName" +
") VALUES (" +
" 'J2COM', 'Jason Price Corporation'" +
")";

mySqlConnection.Open();

// call the ExecuteNonQuery() method of the SqlCommand object
// to run the INSERT statement
int numberOfRows = mySqlCommand.ExecuteNonQuery();
Console.WriteLine("Number of rows added = " + numberOfRows);
DisplayRow(mySqlCommand, "J2COM");

// set the CommandText property of the SqlCommand object to
// an UPDATE statement
mySqlCommand.CommandText =
"UPDATE Customers " +
"SET CompanyName = 'New Company' " +
"WHERE CustomerID = 'J2COM'";

// call the ExecuteNonQuery() method of the SqlCommand object
// to run the UPDATE statement
numberOfRows = mySqlCommand.ExecuteNonQuery();
Console.WriteLine("Number of rows updated = " + numberOfRows);
DisplayRow(mySqlCommand, "J2COM");

// set the CommandText property of the SqlCommand object to
// a DELETE statement

mySqlCommand.CommandText =
"DELETE FROM Customers " +
"WHERE CustomerID = 'J2COM'";

// call the ExecuteNonQuery() method of the SqlCommand object
// to run the DELETE statement
numberOfRows = mySqlCommand.ExecuteNonQuery();
Console.WriteLine("Number of rows deleted = " + numberOfRows);

mySqlConnection.Close();
}
}

The output from this program is as follows:
Number of rows added = 1
mySqlDataReader["CustomerID"] = J2COM
mySqlDataReader["CompanyName"] = Jason Price Corporation
Number of rows updated = 1
mySqlDataReader["CustomerID"] = J2COM
mySqlDataReader["CompanyName"] = New Company
Number of rows deleted = 1
Executing DDL Statements Using the ExecuteNonQuery() Method
In addition to running INSERT, UPDATE, and DELETE statements, you can also use the
ExecuteNonQuery() method to execute DDL statements such as CREATE TABLE.
Let's take a look at an example that executes a CREATE TABLE statement, followed by
an ALTER TABLE statement, followed by a DROP TABLE statement. First, a
Command object is needed:
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();

Next, you set the CommandText property of the Command object to the CREATE

TABLE statement. The following example sets the CommandText property of
mySqlCommand to a CREATE TABLE statement that creates a table named MyPersons
to store information about people:
mySqlCommand.CommandText =
"CREATE TABLE MyPersons (" +
" PersonID int CONSTRAINT PK_Persons PRIMARY KEY," +
" FirstName nvarchar(15) NOT NULL," +
" LastName nvarchar(15) NOT NULL," +
" DateOfBirth datetime" +
")";

×