[英]Identify sql exception in c#?
how to catch sql exception with its error code(error no) to identify which exception is exactly thrown in c# ? 如何使用其错误代码(错误号)捕获sql异常,以确定在c#中确实抛出了哪个异常? for example database is offline or there is reference row in other table so sql wont allow me to delete row but how exactly i could identify what is the problem in catch so that i can display message to the user in my application 例如数据库是脱机的或者其他表中有引用行,所以sql不允许我删除行但是我怎么能确定catch中的问题是什么,以便我可以在我的应用程序中向用户显示消息
You need to put your database code into a try ... catch
block, and (assuming you're using ADO.NET against SQL Server) then catch the SqlException
. 您需要将数据库代码放入try ... catch
块,并且(假设您对SQL Server使用ADO.NET)然后捕获SqlException
。
try
{
// your database code here
}
catch(SqlException sqlEx)
{
foreach(SqlError error in sqlEx.Errors)
{
// you can inspect the individual errors, their code etc. here
}
}
The SqlException
object will contain a collection of SqlError
objects that describe the error that happened in great detail - with line number, error code and everything. 该SqlException
对象将包含集合SqlError
,描述的很详细发生的错误对象-行号,错误代码和一切。
Other databases will have similar constructs - check your docs! 其他数据库将有类似的结构 - 检查你的文档!
在.net异常类层次结构中为每种类型的异常分配了特定的数字,您将在此处找到一些有用的资料
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.