问题描述
我想以不同的方式处理不同的问题,同时进行数据库操作.
I want to handle different problems, while doing database operations, differently.
例如由于错误的数据库凭据或网络问题,操作可能会失败.或者它可能因为查询不正确而失败(如果在int类型列中传递字符串值)
e.g. The operation may fail because of wrong database credentials or due to network problem. Or it may fail because the query is not correct (if string value is being passed in the int type column)
在我的 C# 代码中,我们只有 SqlException
,它具有 SqlErrors
的集合.但是有许多严重级别.
In my C# code, we only have SqlException
which has collection of SqlErrors
. However there are many severity levels.
如何轻松确定 SqlException 的原因?我如何确定异常是由于连接问题或身份验证失败还是由于查询问题.
How can i easily identify the cause of the SqlException ? How can i determine the exception is because of the connectivity problem or authentication failure or because of the problem with the query.
我使用的是 SQL Server 2005.
I am using SQL Server 2005.
推荐答案
试试这样,这将帮助你处理不同的情况.
Try something like this, this will help you in handling different conditions.
像这样使用 try catch 块:
use a try catch block like this:
try
{
...
...
}
catch (SqlException ex)
{
switch (ex.Number)
{
case 4060: // Invalid Database
....
break;
case 18456: // Login Failed
....
break;
case 547: // ForeignKey Violation
....
break;
case 2627:
// Unique Index/ Primary key Violation/ Constriant Violation
....
break;
case 2601: // Unique Index/Constriant Violation
....
break;
default:
....
break;
}
}
这篇关于如何知道由于哪个 SqlException 被抛出而导致的实际问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!