我怎么能知道一个SQLException被抛出,因为外键冲突? [英] How can I know if an SQLexception was thrown because of foreign key violation?

查看:269
本文介绍了我怎么能知道一个SQLException被抛出,因为外键冲突?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想告诉大家,一个纪录没有被删除,因为它有子数据的用户,但我怎么能肯定的是,抛出异常,因为一个外键冲突?我看到有一个用于所有SQL异常抛出SQLException类。

I want to tell the user that a record was not deleted because it has child data, but how can I be sure that the exception was thrown because of a foreign key violation? I see that there a sqlexception class that is used for all sql exception.

推荐答案

您使用的是SQL Server的假设。

Assume you're using SQL Server.

使用德谷歌 - <一个href="http://blogs.msdn.com/tomholl/archive/2007/08/01/mapping-sql-server-errors-to-net-exceptions-the-fun-way.aspx" rel="nofollow">http://blogs.msdn.com/tomholl/archive/2007/08/01/mapping-sql-server-errors-to-net-exceptions-the-fun-way.aspx

try
{
    # SQL Stuff
}
catch (SqlException ex)
{
    if (ex.Errors.Count > 0) // Assume the interesting stuff is in the first error
    {
        switch (ex.Errors[0].Number)
        {
            case 547: // Foreign Key violation
                throw new InvalidOperationException("Some helpful description", ex);
                break;
            case 2601: // Primary key violation
                throw new DuplicateRecordException("Some other helpful description", ex);
                break;
            default:
                throw new DataAccessException(ex);
        }
    }

}

案例547是你的男人。

Case 547 is your man.

更新以上是样品code和不应使用。请按照链接来解释为什么。

UPDATE The above is sample code and should not be used. Please follow the link as to explain why.

这篇关于我怎么能知道一个SQLException被抛出,因为外键冲突?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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