How to know actual problem because of which SqlException is thrown?(如何知道由于哪个 SqlException 被抛出而导致的实际问题?)
问题描述
我想以不同的方式处理不同的问题,同时进行数据库操作.
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 被抛出而导致的实际问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何知道由于哪个 SqlException 被抛出而导致的实际问题?


- 带问号的 nvarchar 列结果 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- 使用 rss + c# 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01