有没有办法在C#中测试特定的sql异常类型?

时间:2012-06-25 14:20:17

标签: c# asp.net sql-server

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

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

我可以查看异常错误字符串并测试是否存在单词,但我不确定是否有更好的方法来检查特定的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)

3 个答案:

答案 0 :(得分:14)

  

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

是的,您可以检查SqlException的Number

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查询相关的多个错误。

答案 1 :(得分:1)

看一下SqlException

catch(SqlException se)
{
    if(se.Number == x)
    {
        //Show message
    }
}

答案 2 :(得分: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();
}