繁体   English   中英

使用 ExecuteScalar 在客户端(C# Winform)的 SQL 服务器中从 try/catch 中捕获错误

[英]Catch an error from try/catch in SQL Server at client side (C# Winform) using ExecuteScalar

我正在使用 SQL 服务器作为后端在 C# 中开发 windows 应用程序。 我必须向应用程序显示在存储过程中生成的错误消息,该错误消息在 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
        }
        Console.WriteLine("{0} rows read", rowCount);
    }
}
catch
{
    throw;
}

以下是可能发生未检测到的 SqlExceptions 的常见情况。 如果不采用上述防御性编程技术,则编写 T-SQL 代码以确保不会发生这些情况很重要。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM