判断SQL 中SELECT 语句所影响的行

首先看看ExecuteNonQuery()与ExecuteNonQuery()的返回值。

SqlCommand.ExecuteNonQuery() 方法仅对于 UPDATE、INSERT 和 DELETE 语句,返回值为该命令所影响的行数。对于所有其他类型的语句,返回值为 -1。如果发生回滚,返回值也为 -1

 

SqlCoCommand.ExecuteScalar ()方法执行查询,并返回查询所返回的结果集中第一行的第一列,忽略额外的列或行。如果为聚合查询则返回一个聚合值。

 

所以在查询表中是否有(某条)数据的时候,一定不能用 cmd.ExecuteNonQuery()通过返回值是否大于0来判断。

 

解决方案:

1. SqlCoCommand.ExecuteScalar ()方法 中使用 聚合查询

cmd.CommandText = " select count(*) from users where id = sa and password=123;"

 

int count = (int)cmd.ExecuteScalar() ;

 

If(count>=1)

 

       return true;

 

else

 

      return false;

 

2. 用ExecuteReader()方法返回一个reader

cmd.CommandText = " select count(*) from users where id = sa and password=123;"

 

SqlDataReader dreader = Cmd.ExecuteReader();

 

if(dreader.Read()==false)

 

      return false ;

 

else

 

     return true ;

posted @ 2011-01-11 09:50  快乐的langYa  阅读(630)  评论(0编辑  收藏  举报