如何:将数据集更改保存到数据库中

更新:2007 年 11 月

在修改并验证了数据集中的数据后,可能需要将更新后的数据发回数据库。为了向数据库发送修改的数据,您可调用 TableAdapter 或数据适配器的 Update 方法。此适配器的 Update 方法将更新单个数据表并根据该表中每个数据行的 RowState 执行正确的命令(INSERT、UPDATE 或 DELETE)。

保存相关表中的数据时,Visual Studio 2008 提供的新 TableAdapterManager 组件可帮助根据数据库中定义的外键约束,按照正确的顺序执行保存。有关更多信息,请参见分层更新概述

说明:

由于尝试使用数据集的内容更新数据源可能会导致错误,因此应将调用该适配器的 Update 方法的代码放置在 try/catch 块的内部。

根据您的业务需要,更新数据源的确切过程可能会有所不同,但是您的应用程序应该包括以下步骤:

  1. 执行 try/catch 块中尝试将更新发送到数据库的代码。

  2. 如果捕获到异常,则找到引发错误的数据行。有关更多信息,请参见 如何:定位出错的行

  3. 协调数据行中的问题(在可能的情况下以编程的方式进行,或者将无效的行显示给用户进行修改),然后重新尝试更新(HasErrors 属性,GetErrors 方法)。

将数据保存到数据库

调用 TableAdapter 或数据适配器的 Update 方法,将包含要写入值的数据表的名称传递给数据库。有关将单个数据表中的数据保存回数据库的更多信息,请参见 演练:将数据保存到数据库(单个表)

通过 TableAdapter 用数据集更新数据库

  • 在 try/catch 块中包含 TableAdapter.Update 方法。下面的示例演示如何尝试用 NorthwindDataSet 中的 Customers 表的内容进行更新。

    Try
        Me.Validate()
        Me.CustomersBindingSource.EndEdit()
        Me.CustomersTableAdapter.Update(Me.NorthwindDataSet.Customers)
        MsgBox("Update successful")
    
    Catch ex As Exception
        MsgBox("Update failed")
    End Try
    
    try
    {
        this.Validate();
        this.customersBindingSource.EndEdit();
        this.customersTableAdapter.Update(this.northwindDataSet.Customers);
        MessageBox.Show("Update successful");
    }
    catch (System.Exception ex)
    {
        MessageBox.Show("Update failed");
    }
    

使用数据适配器用数据集更新数据库

  • 在 try/catch 块中包含 DataAdapter.Update 方法。下面的示例演示如何尝试用 DataSet1 中的 Table1 的内容对数据源进行更新。

    Try
        SqlDataAdapter1.Update(Dataset1.Tables("Table1"))
    
    Catch x As Exception
        ' Error during Update, add code to locate error, reconcile 
        ' and try to update again.
    End Try
    
    try
    {
        SqlDataAdapter1.Update(Dataset1.Tables["Table1"]);
    }
    catch (Exception e)
    {
        // Error during Update, add code to locate error, reconcile 
        // and try to update again.
    }
    

更新数据集中的两个相关表

当更新数据集中的相关表时,务必要以正确的顺序进行更新,以减小违反引用完整性约束的可能性。命令执行的顺序也将遵循数据集中 DataRowCollection 的索引的顺序。为了防止引发数据完整性错误,最佳的做法是按照下面的顺序更新数据库:

  1. 子表:删除记录。

  2. 父表:插入、更新和删除记录。

  3. 子表:插入和更新记录。

有关从多个表保存数据的详细信息,请参见 演练:将数据保存到数据库(多个表)

如果要更新两个或更多相关表,则应将所有更新逻辑包括在一个事务内。事务是指一个过程,它首先确保对数据库的所有相关更改均可成功完成,然后再提交更改。有关更多信息,请参见事务 (ADO.NET)

使用 TableAdapter 更新两个相关表

  1. 创建三个临时 DataTable 以保存不同的记录。

  2. 从 try/catch 块中为每个子行集调用 Update 方法。如果出现更新错误,建议的操作过程则将分支并解除错误。

  3. 将更改从数据集提交到数据库。

  4. 处置临时数据表以释放资源。

    Private Sub UpdateDB()
        Dim deletedChildRecords As NorthwindDataSet.OrdersDataTable = _
            CType(NorthwindDataSet.Orders.GetChanges(Data.DataRowState.Deleted), NorthwindDataSet.OrdersDataTable)
    
        Dim newChildRecords As NorthwindDataSet.OrdersDataTable = _
            CType(NorthwindDataSet.Orders.GetChanges(Data.DataRowState.Added), NorthwindDataSet.OrdersDataTable)
    
        Dim modifiedChildRecords As NorthwindDataSet.OrdersDataTable = _
            CType(NorthwindDataSet.Orders.GetChanges(Data.DataRowState.Modified), NorthwindDataSet.OrdersDataTable)
    
        Try
            If deletedChildRecords IsNot Nothing Then
                OrdersTableAdapter.Update(deletedChildRecords)
            End If
    
            CustomersTableAdapter.Update(NorthwindDataSet.Customers)
    
            If newChildRecords IsNot Nothing Then
                OrdersTableAdapter.Update(newChildRecords)
            End If
    
            If modifiedChildRecords IsNot Nothing Then
                OrdersTableAdapter.Update(modifiedChildRecords)
            End If
    
            NorthwindDataSet.AcceptChanges()
    
        Catch ex As Exception
            MessageBox.Show("An error occurred during the update process")
            ' Add code to handle error here.
    
        Finally
            If deletedChildRecords IsNot Nothing Then
                deletedChildRecords.Dispose()
            End If
    
            If newChildRecords IsNot Nothing Then
                newChildRecords.Dispose()
            End If
    
            If modifiedChildRecords IsNot Nothing Then
                modifiedChildRecords.Dispose()
            End If
    
        End Try
    End Sub
    
    void UpdateDB()
    {
        NorthwindDataSet.OrdersDataTable deletedChildRecords = 
            (NorthwindDataSet.OrdersDataTable)northwindDataSet.Orders.GetChanges(DataRowState.Deleted);
    
        NorthwindDataSet.OrdersDataTable newChildRecords = 
            (NorthwindDataSet.OrdersDataTable)northwindDataSet.Orders.GetChanges(DataRowState.Added);
    
        NorthwindDataSet.OrdersDataTable modifiedChildRecords = 
            (NorthwindDataSet.OrdersDataTable)northwindDataSet.Orders.GetChanges(DataRowState.Modified);
    
        try
        {
            if (deletedChildRecords != null)
            {
                ordersTableAdapter.Update(deletedChildRecords);
            }
    
            customersTableAdapter.Update(northwindDataSet.Customers);
    
            if (newChildRecords != null)
            {
                ordersTableAdapter.Update(newChildRecords);
            }
    
            if (modifiedChildRecords != null)
            {
                ordersTableAdapter.Update(modifiedChildRecords);
            }
    
            northwindDataSet.AcceptChanges();
        }
    
        catch (Exception ex)
        {
            MessageBox.Show("An error occurred during the update process");
            // Add code to handle error here.
        }
    
        finally
        {
            if (deletedChildRecords != null)
            {
                deletedChildRecords.Dispose();
            }
            if (newChildRecords != null)
            {
                newChildRecords.Dispose();
            }
            if (modifiedChildRecords != null)
            {
                modifiedChildRecords.Dispose();
            }
        }
    }
    

使用数据适配器更新两个相关表

  • 调用每个数据适配器的 Update 方法。

    下面的示例显示如何用包含相关表的数据集更新数据源。为了遵循上面的顺序,将创建三个临时 DataTable 来保存不同的记录。然后,将在 try/catch 块中对每个子行集调用 Update 方法。如果出现更新错误,建议的操作过程则将分支并解除错误。然后,数据集提交更改。最后,处置临时数据表以释放资源。

    Private Sub UpdateDB()
        Dim DeletedChildRecords As DataTable = _
            dsNorthwind1.Orders.GetChanges(DataRowState.Deleted)
    
        Dim NewChildRecords As DataTable = _
            dsNorthwind1.Orders.GetChanges(DataRowState.Added)
    
        Dim ModifiedChildRecords As DataTable = _
            dsNorthwind1.Orders.GetChanges(DataRowState.Modified)
    
        Try
            If Not DeletedChildRecords Is Nothing Then
                daOrders.Update(DeletedChildRecords)
            End If
    
            daCustomers.Update(dsNorthwind1, "Customers")
    
            If Not NewChildRecords Is Nothing Then
                daOrders.Update(NewChildRecords)
            End If
    
            If Not ModifiedChildRecords Is Nothing Then
                daOrders.Update(ModifiedChildRecords)
            End If
    
            dsNorthwind1.AcceptChanges()
    
        Catch ex As Exception
            ' Update error, resolve and try again
    
        Finally
            If Not DeletedChildRecords Is Nothing Then
                DeletedChildRecords.Dispose()
            End If
    
            If Not NewChildRecords Is Nothing Then
                NewChildRecords.Dispose()
            End If
    
            If Not ModifiedChildRecords Is Nothing Then
                ModifiedChildRecords.Dispose()
            End If
        End Try
    End Sub
    
    void UpdateDB()
    {
        System.Data.DataTable DeletedChildRecords = 
            dsNorthwind1.Orders.GetChanges(System.Data.DataRowState.Deleted);
    
        System.Data.DataTable NewChildRecords = 
            dsNorthwind1.Orders.GetChanges(System.Data.DataRowState.Added);
    
        System.Data.DataTable ModifiedChildRecords = 
            dsNorthwind1.Orders.GetChanges(System.Data.DataRowState.Modified);
    
        try
        {
            if (DeletedChildRecords != null)
            {
                daOrders.Update(DeletedChildRecords);
            }
            if (NewChildRecords != null)
            {
                daOrders.Update(NewChildRecords);
            }
            if (ModifiedChildRecords != null)
            {
                daOrders.Update(ModifiedChildRecords);
            }
    
            dsNorthwind1.AcceptChanges();
        }
    
        catch (Exception ex)
        {
            // Update error, resolve and try again
        }
    
        finally
        {
            if (DeletedChildRecords != null)
            {
                DeletedChildRecords.Dispose();
            }
            if (NewChildRecords != null)
            {
                NewChildRecords.Dispose();
            }
            if (ModifiedChildRecords != null)
            {
                ModifiedChildRecords.Dispose();
            }
        }
    }
    

请参见

概念

数据中的新增功能

“显示数据”概述

其他资源

数据演练

连接到 Visual Studio 中的数据

准备应用程序以接收数据

将数据获取到应用程序

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

在应用程序中编辑数据

验证数据

保存数据