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

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

  1. try/catch 块中调用适配器的 Update 方法。

  2. 如果捕获到异常,则找到引发错误的数据行。

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

    Try
        Me.Validate()
        Me.CustomersBindingSource.EndEdit()
        Me.CustomersTableAdapter.Update(Me.NorthwindDataSet.Customers)
        MsgBox("Update successful")
    
    Catch ex As Exception
        MsgBox("Update failed")
    End Try

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

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

  1. 子表:删除记录。

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

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

  4. 使用 TableAdapter 更新两个相关表

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

    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




原文地址:https://www.cnblogs.com/tanqianqian/p/5975056.html