如何在使用 ExecuteNonQuery() 时收到错误消息? [英] How can I get an error message that happens when using ExecuteNonQuery()?

查看:18
本文介绍了如何在使用 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() 时收到错误消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆