使用ExecuteScalar在客户端(C#Winform)的SQL Server中捕获try/Catch中的错误



我正在用C#开发windows应用程序,SQL Server作为后端。我必须向应用程序显示存储过程中生成的错误消息,该消息在try-catch块中处理。如果我们使用ExecuteNonQuery(),它可以正常工作。存储过程将返回一个ID,因此我使用ExecuteScalar(),并且不会显示来自catch块的错误消息。

对于ExecuteScalar,如果我们删除try-catch块,也会显示错误。

它不会显示在客户端。

begin
begin try
select 1/0
select 10
end try
begin catch
raiserror (' Some Error Message', 16, 10)
end catch
end

它将显示在客户端。

begin
select 1/0
raiserror (' Some Error Message', 16, 10)
select 10
end

请提供解决方案。

为了确保检测到SqlException,客户端必须使用所有结果集。ExecuteScalar()只返回结果的第一行/列,但不使用结果的剩余部分,因此客户端API不会引发异常。

此示例代码将通过避免ExecuteScalar()并消耗所有结果来引发错误:

try
{
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(sqlBatchText, connection))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
scalarIntResult = reader.GetInt32(0);
}
while (reader.Read()) { }; //consume remainder of first result
while (reader.NextResult()) { }; //consume subsequent results
}
}
}
catch
{
throw;
}

以下是可能发生未检测到的SqlException的常见情况。如果没有采用如上所述的防御性编程技术,那么对T-SQL进行编码以确保这些场景不会发生是很重要的。

  1. 执行行返回语句时,T-SQLTRY/CATCH捕获到一个错误
  2. 成功执行行返回语句后发生错误
  3. 返回行计数消息后会发生错误(取决于客户端API(

有关更多详细信息,请参阅本文。

最新更新