4

从数据库中删除记录时,偶尔会遇到引用约束异常。

以下是异常详细信息。当异常与外键约束错误特别相关时,是否可以向用户显示消息?

我可以查看异常错误字符串并测试是否存在单词,但我不确定是否有更好的方法来检查特定的 SQL 错误。

谢谢凯文

Message: The DELETE statement conflicted with the REFERENCE constraint "FK_Customers_PaymentTerms". The conflict occurred in database "kd", table "dbo.Customers", column 'CstPtmID'.
The statement has been terminated.
Source: .Net SqlClient Data Provider
TargetSite: Void OnError(System.Data.SqlClient.SqlException, Boolean)
StackTrace:    at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
   at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
   at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe)
   at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
   at System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary`2 identifierValues, List`1 generatedValues)
   at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
4

3 回答 3

14

当异常与外键约束错误特别相关时,是否可以向用户显示消息?

是的,您可以检查NumberSqlException:

try
{
    // do your database query
}
catch (SqlException ex)
{
    if (ex.Number == .....)
    {
        // Can't remember from the top of my head the exact error code 
        // that is triggered in this situation. Just check it.
    }
}

如评论部分所述,最好检查Errors数组,因为可能存在与单个 SQL 查询相关的多个错误。

于 2012-06-25T14:23:04.087 回答
1

看看SqlException下

catch(SqlException se)
{
    if(se.Number == x)
    {
        //Show message
    }
}
于 2012-06-25T14:25:16.697 回答
1

使用Errors集合显示错误:

public static void ShowSqlException(string connectionString)
{
    string queryString = "EXECUTE NonExistantStoredProcedure";

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlCommand command = new SqlCommand(queryString, connection);
        try
        {
            command.Connection.Open();
            command.ExecuteNonQuery();
        }
        catch (SqlException ex)
        {
            DisplaySqlErrors(ex);
        }
    }
}

private static void DisplaySqlErrors(SqlException exception)
{
    for (int i = 0; i < exception.Errors.Count; i++)
    {
        Console.WriteLine("Index #" + i + "\n" +
            "Error: " + exception.Errors[i].ToString() + "\n") +
            "Number: " + exception.Errors[i].Number.ToString() + "\n");
    }
    Console.ReadLine();
}
于 2012-06-25T14:33:04.507 回答