How can I get an error message that happens when using ExecuteNonQuery()?(如何在使用 ExecuteNonQuery() 时收到错误消息?)
问题描述
我正在以这种方式执行命令:
I am executing a command in this way :
var Command = new SqlCommand(cmdText, Connection, tr);
Command.ExecuteNonQuery();
在命令中有一个错误,但是 .NET 不会抛出任何错误消息.我怎么知道命令没有正确执行,以及如何获取异常?
In the command there is an error, however .NET does not throw any error message. How could I know that the command did not executed properly, and how to get the exception?
推荐答案
如果你的错误的严重性为 16 或更高,你只会在 C# 中得到一个异常.如果您使用的是 PRINT,则在 .NET 中不会出现异常.
You'll only get an exception in C# if your error's severity is 16 or above. If you are using a PRINT, you won't get an exception in .NET.
如果您可以编辑 raise 错误代码,这将导致 C# 中的 SqlException:
If you can edit the raise error code, this would cause a SqlException in C#:
RAISERROR('Some error message', 16, 1)
然后您可以访问 SqlException.Errors 集合中的每个单独的错误.
You can then get to each individual error in the SqlException.Errors collection.
附带说明 - 如果您之后不直接 RETURN,SQL Server 将在 RAISERROR 之后继续运行命令.如果不返回,可能会返回多个错误.
Just a side-note - SQL Server will continue to run commands after the RAISERROR if you don't RETURN directly afterwards. If you don't return, you can get multiple errors back.
这篇关于如何在使用 ExecuteNonQuery() 时收到错误消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在使用 ExecuteNonQuery() 时收到错误消息?
基础教程推荐
- WPF 模态进度窗口 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
