The ExecuteNonQuery () method is used to Update data. Generally, it uses the Update, Insert, and Delete statements to operate on the database. The returned values of the methods mean: For Update, Insert, if the Delete statement is successfully executed, the returned value is the number of rows affected by the command. If the number of affected rows is 0, the returned value is 0. If the data operation is rolled back, the returned value is-1, this update operation should be normal and good if it is usually used to determine whether it is greater than 0, but other operations, such as operations on the database structure, if-1 is returned when the operation is successful, this is a little different from our usual way of thinking, so pay attention to it. For example, you can add a data table Create operation to the database, -1 is returned when the data table is created successfully. If the operation fails (such as the data table already exists), an exception often occurs. Therefore, it is best to use the try -- catch -- Statement for fault tolerance when performing this operation.
For example, ExecuteNonQuery () is used to execute the create operation.
[Code]
SqlConnection conn = new SqlConnection ("Data Source =.; Initial Catalog = PSDB; Integrated Security = SSPI ");
String str = "create table aaa (" +
"[ID] [int] IDENTITY (1, 1) not null," +
"[BasicID] [int] NULL," +
"[AdoptedName] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL," +
"[AdoptedSex] [char] (2) COLLATE Chinese_PRC_CI_AS NULL," +
"[AdoptBirthday] [smalldatetime] NULL," +
"[AdoptedType] [varchar] (100) COLLATE Chinese_PRC_CI_AS NULL," +
"[ApprTime] [smalldatetime] NULL," +
"[Remarker] [varchar] (500) COLLATE Chinese_PRC_CI_AS NULL" +
") ON [PRIMARY]";
SqlCommand comm = new SqlCommand (str, conn );
Int I = 10;
Try
{
Conn. Open ();
I = comm. ExecuteNonQuery ();
Conn. Close ();
}
Catch (Exception ex)
{
Response. Write (ex. Message );
}
Response. Write (I. ToString ());
[Code]
If the execution is successful, the returned value is-1. If the data table already exists, an exception is returned: an object named 'aaa' already exists in the database.