Home  >  Article  >  Database  >  mssql server ExecuteNonQuery()注意问题

mssql server ExecuteNonQuery()注意问题

WBOY
WBOYOriginal
2016-06-07 17:47:121123browse

ExecuteNonQuery()方法主要用户更新数据,通常它使用Update,Insert,Delete语句来操作,其方法返回值意义:对于 Update,Insert,Delete 语句 执行成功是返回值为该命令所影响的行数,如果影响的行数为0时返回的值为0,如果数据操作回滚得话返回值为-1,对于这种更新操作 用我们平时所用的是否大于0的判断操作应该没有问题而且比较好,但是对于其他的操作如对数据库结构的操作,如果操作成功时返回的却是-1,这种情况跟我们平时的思维方式有点差距所以应该好好的注意了,例如对数据库共添加一个数据表的Create操作,当创建数据表成功时返回-1,如果操作失败的话(如数据表已经存在)往往会发生异常,所以执行这种操作时最好用try--catch--语句来容错。


例如用ExecuteNonQuery()方法执行create操作

 

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 ," +
"[Remark] [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());

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn