David Qian

If there's a problem, just resolve it yourself
为什么 SqlCommand.ExecuteNonQuery() 方法返回 -1?

不知道大家在使用ExecuteNonQuery方法的时候有没有碰到过返回-1的情况。ExecuteNonQuery方法返回增删改时,受影响的行数。那怎么会返回-1呢?查了一些资料后终于得知返回-1的原因。

在进行增删改时,数据库能为我们统计受影响行数的前提条件是,关闭NOCOUNT,即 Set nocount off。默认情况下,它是关闭的,即我们是可以得到受影响的行数的。你可以测试如下(加与不加set nocount on是有区别的):

SqlCommand cmd = new SqlCommand("set nocount on; insert into test values ('test')", con);
int rows = cmd.ExecuteNonQuery();

有的人就说了,我仅仅是调用一个简单的存储过程,怎么还是返回-1呢?这个是由于Visual Studio引起的。

我们在Visual Studio中写了一个存储过程时,它会被默认加上set nocount on。这样就导致了调用存储过程时始终得不到影响的行数,而返回-1。不过我在Visual Studio 2008 Team Suit中测试了下,这个问题不存在了。可能以前的版本有这样的问题吧(未测试),碰到这种情况就多留意些。

Have a nice day!

posted on 2009-02-12 10:17  Wencui  阅读(7890)  评论(9编辑  收藏  举报