代码之家  ›  专栏  ›  技术社区  ›  adopilot

从C中的SQL捕获引用约束异常#

  •  3
  • adopilot  · 技术社区  · 15 年前

    当我从C代码中删除带有引用约束的数据时,捕获抛出SQL Server的异常的正确方法是什么?
    我想向用户显示如下消息:
    “无法删除数据,因为已使用”
    ,而不是像这样显示消息:

    The DELETE statement conflicted with the REFERENCE constraint ... The conflict ccurred*in database "rampa", table "dbo.doc", column 'kartica_id'.
    
    2 回复  |  直到 15 年前
        1
  •  6
  •   Ivan Ferić    15 年前

    try
    {
       //Execute delete statement
    }
    catch (SqlException sqlEx)
    {
       //Handle exception
    }
    finally
    {
       //Close connection
    }
    

    SqlException SqlException.Number here

        2
  •  2
  •   Steve Townsend    15 年前

    ConstraintException

    using System.Data;
    
    try
    {
      // code that violates constraint
    }
    catch (ConstraintException exc)
    {
      // build output message you wish using exc.Message and other fields,
      // return cleanly or rethrow as your own exception
    }