当使用ExecuteNonQuery执行SELECT SQL语句时,如何检查是否返回了零行?
当使用ExecuteNonQuery执行SELECT SQL语句时,如何检查是否返回了零行?
ExecuteNonQuery方法
返回由INSERT
、UPDATE
或DELETE
语句影响的行数。此方法用于执行DML(数据操作语言)语句,正如前面所述。
ExecuteReader方法
将返回SELECT
的结果集。当您查询一堆结果(例如来自表、视图等的行)时,请使用此方法。
ExecuteScalar方法
将从SELECT
语句中的第一行第一列返回单个值。当您只期望从查询中返回一个值时,请使用此方法。
简而言之,在使用ExecuteNonQuery
方法时,没有结果来自SELECT
语句是正常的。请改用ExecuteReader
。使用ExecuteReader
方法,您将通过返回的SqlDataReader
对象的实例知道返回了多少行。
int rows = 0;
if (reader.HasRows)
while (reader.Read())
rows++;
return rows; // Returns the number of rows read from the reader.
我看不到任何方法来实现这一点。使用ExecuteScalar
和select count(*) where
来计算与原始SELECT查询的条件匹配的行数。下面是一个示例,摘自此处:
using (SqlCommand thisCommand =
new SqlCommand("SELECT COUNT(*) FROM Employee", thisConnection))
{
Console.WriteLine("Number of Employees is: {0}",
thisCommand.ExecuteScalar());
}
ExecuteReader
了。请使用ExecuteReader
方法代替。这将返回一个SqlDataReader
,该对象包含一个HasRows
属性。
ExecuteNonQuery
不应用于SELECT
语句。
CREATE PROCEDURE spMyStoredProcedure
(
@TotalRows int output
)
AS
BEGIN
SELECT * FROM MyTable; //see extra note about this line below.
SELECT @TotalRows COUNT(*) FROM MyTable;
END
Dim cn As SqlConnection, cm As SqlCommand, dr As SqlDataReader
Dim myCount As Int32
cn = New SqlConnection("MyConnectionString")
cn.Open() //I open my connection beforehand, but a lot of people open it right before executing the queries. Not sure if it matters.
cm = New SqlCommand("spMyStoredProcedure", cn)
cm.CommandType = CommandType.StoredProcedure
cm.Parameters.Add("@TotalRows", SqlDbType.Int).Direction = ParameterDirection.Output
cm.ExecuteNonQuery()
myCount = CType(cm.Parameters("@TotalRows").Value, Integer)
If myCount > 0 Then
//Do something.
End If
dr = cm.ExecuteReader()
If dr.HasRows Then
//Return the actual query results using the stored procedure's 1st SELECT statement
End If
dr.Close()
cn.Close()
dr = Nothing
cm = Nothing
cn = Nothing
就是这样。
另外一点说明,我假设你可能希望获取"MyCount"的数量来执行其他操作,而不仅仅是确定是否继续返回查询结果。原因是因为使用这种方法,你实际上不需要这样做。由于在获取计数后我使用了"ExecuteReader"方法,我可以利用数据读取器的"HasRows"属性来确定是否继续返回预期的数据集。但是,要返回一个数据集,你需要一个返回数据集的SELECT语句,这就是我在存储过程中使用第一个SELECT语句的原因。
顺便说一下,使用"ExecuteNonQuery"方法的好处是,在关闭DataReader之前,你可以使用它来获取总行数(你不能在关闭DataReader之前读取输出参数,这就是我试图做的事情,这种方法可以解决这个问题)。我不确定这样做是否会影响性能或存在缺陷,但像我说的那样...对我来说有效。=D
command
有参数吗? - AJ.