Executing Commands that Modify Information in the Database

Chia sẻ: Tuan Nghia | Ngày: | Loại File: PDF | Số trang:8

0
47
lượt xem
4
download

Executing Commands that Modify Information in the Database

Mô tả tài liệu
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

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

Chủ đề:
Lưu

Nội dung Text: Executing Commands that Modify Information in the Database

  1. 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 DESCRIPTION TYPE 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 =
  2. "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
  3. 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 =
  4. 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
  5. 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" + ")";
  6. Next, you call the ExecuteNonQuery() method to execute the CREATE TABLE statement: int result = mySqlCommand.ExecuteNonQuery(); Since a CREATE TABLE statement doesn't affect any rows, ExecuteNonQuery() returns the value -1. The next example executes an ALTER TABLE statement to add a foreign key constraint to the MyPersons table: mySqlCommand.CommandText = "ALTER TABLE MyPersons " + "ADD EmployerID nchar(5) CONSTRAINT FK_Persons_Customers " + "REFERENCES Customers(CustomerID)"; result = mySqlCommand.ExecuteNonQuery(); Once again, ExecuteNonQuery() returns -1 since the ALTER TABLE statement doesn't affect any rows. The final example executes a DROP TABLE statement to drop the MyPersons table: mySqlCommand.CommandText = "DROP TABLE MyPersons"; result = mySqlCommand.ExecuteNonQuery(); ExecuteNonQuery() returns -1 again. Listing 8.8 illustrates the use of the ExecuteNonQuery() method to execute the DDL statements shown in this section. Listing 8.8: EXECUTEDDL.CS /* ExecuteDDL.cs illustrates how to use the ExecuteNonQuery() method to run DDL statements */ using System; using System.Data; using System.Data.SqlClient; class ExecuteDDL { public static void Main()
  7. { SqlConnection mySqlConnection = new SqlConnection( "server=localhost;database=Northwind;uid=sa;pwd=sa" ); SqlCommand mySqlCommand = mySqlConnection.CreateCommand(); // set the CommandText property of the SqlCommand object to // a CREATE TABLE statement mySqlCommand.CommandText = "CREATE TABLE MyPersons (" + " PersonID int CONSTRAINT PK_Persons PRIMARY KEY," + " FirstName nvarchar(15) NOT NULL," + " LastName nvarchar(15) NOT NULL," + " DateOfBirth datetime" + ")"; mySqlConnection.Open(); // call the ExecuteNonQuery() method of the SqlCommand object // to run the CREATE TABLE statement Console.WriteLine("Creating MyPersons table"); int result = mySqlCommand.ExecuteNonQuery(); Console.WriteLine("mySqlCommand.ExecuteNonQuery() = " + result); // set the CommandText property of the SqlCommand object to // an ALTER TABLE statement mySqlCommand.CommandText = "ALTER TABLE MyPersons " + "ADD EmployerID nchar(5) CONSTRAINT FK_Persons_Customers " + "REFERENCES Customers(CustomerID)"; // call the ExecuteNonQuery() method of the SqlCommand object // to run the ALTER TABLE statement Console.WriteLine("Altering MyPersons table"); result = mySqlCommand.ExecuteNonQuery(); Console.WriteLine("mySqlCommand.ExecuteNonQuery() = " + result); // set the CommandText property of the SqlCommand object to // a DROP TABLE statement mySqlCommand.CommandText = "DROP TABLE MyPersons";
  8. // call the ExecuteNonQuery() method of the SqlCommand object // to run the DROP TABLE statement Console.WriteLine("Dropping MyPersons table"); result = mySqlCommand.ExecuteNonQuery(); Console.WriteLine("mySqlCommand.ExecuteNonQuery() = " + result); mySqlConnection.Close(); } } The output from this program is as follows: Creating MyPersons table mySqlCommand.ExecuteNonQuery() = -1 Altering MyPersons table mySqlCommand.ExecuteNonQuery() = -1 Dropping MyPersons table mySqlCommand.ExecuteNonQuery() = -1
Đồng bộ tài khoản