如何:处理并发错误

更新:2007 年 11 月

可以捕获 DBConcurrencyException 对象以帮助解决由并发冲突引发的问题。DBConcurrencyException 对象返回导致错误的数据行。有关更多信息,请参见 DBConcurrencyException 成员

下面的示例试图用 try/catch 块内 NorthwindDataSet 的内容更新数据源,如果引发了错误,则显示错误信息以及有问题数据行的第一列。

说明:

下面的代码举例说明了一种处理数据库更新错误的策略。该代码假定了以下内容:一个与数据库的现有连接、一个现有数据库,以及更新命令的执行将引发并发冲突的假设。有关更多信息及完整示例,请参见演练:处理并发异常

解决并发冲突

  1. 执行用于在 try/catch 块中更新数据库的命令。

  2. 如果引发异常,则检查 catch 语句的 Row 属性,以确定导致冲突的原因。

  3. 根据您的应用程序业务规则添加代码来解决错误。

    下面的代码将 CustomersTableAdapter 和 NorthwindDataSet 用作应用程序中适配器和数据集的示例。

    Try
        CustomersTableAdapter.Update(NorthwindDataSet)
    
    Catch ex As DBConcurrencyException
    
        Dim customErrorMessage As String
        customErrorMessage = "Concurrency violation" & vbCrLf
        customErrorMessage += CType(ex.Row.Item(0), String)
        MessageBox.Show(customErrorMessage)
    
        ' Add business logic code to resolve the concurrency violation...
    
    End Try
    
    try
    {
        customersTableAdapter.Update(northwindDataSet);
    }
    catch (DBConcurrencyException ex)
    {
        string customErrorMessage;
        customErrorMessage = "Concurrency violation\n";
        customErrorMessage += ex.Row[0].ToString();
    
        // Add business logic code to resolve the concurrency violation...
    }
    

请参见

概念

数据中的新增功能

“显示数据”概述

其他资源

数据演练

连接到 Visual Studio 中的数据

准备应用程序以接收数据

将数据获取到应用程序

在 Windows 应用程序中的窗体上显示数据

在应用程序中编辑数据

验证数据

保存数据