在Visual Basic中更新表适配器时出错

时间:2011-10-04 14:53:56

标签: vb.net dataset

我正在尝试通过Visual Basic表单编码来提高编程能力。我已经创建了一个数据库并将其链接到VB表单,我现在正在编写一种写入数据库而不是读取的方法。

我正在填充一个数组,该数组又逐行放入数据集中,但是当尝试“更新”表适配器时,我收到以下错误:

  

在传递带有修改行的DataRow集合时,更新需要有效的UpdateCommand。

我认为这与主键有关,我的适配器正在更新的表没有主键,因为它涉及与包含主键的另一个表的关系。如何在不收到此错误的情况下更新表适配器?感谢。

1 个答案:

答案 0 :(得分:1)

您提到的错误消息与您尝试更新的表上的主键无关,而是抱怨,因为您没有为适配器提供可用于更新基础表的有效命令。

如果您尝试插入或删除新行而未在适配器上指定插入或删除命令,则会遇到相同的错误。

要解决此问题,请将UpdateCommand属性初始化为有意义的属性,例如:

'Open connection
Using Conn as new OleDbConnection("connection string")

  'This is the command that will update your table in the database
  Using UpdateCmd = Conn.CreateCommand()

    UpdateCmd.CommandText = "update yourtable set col1 = ?, col2 = ?"

    'Create a parameter to pass in the value of the "col1" column on "yourtable"
    Dim ColOneParam = UpdateCmd.Parameters.Add("@Col1", OleDbType.Integer)
    ColOneParam.SourceColumn = "Name of column in DataTable which corresponds to col1"

    'Create a parameter to pass in the value of the "col2" column on "yourtable"
    Dim ColTwoParam = UpdateCmd.Parameters.Add("@Col2", OleDbType.Integer)
    ColTwoParam.SourceColumn = "Name of column in DataTable which corresponds to col2"

    'Data adapter which will perform the specified update command for each 
    'newly inserted row
    Using Adapter As New OleDbDataAdapter

      'Set the update command on the adapter, if you omit this line you'll
      'encounter the original error you mentioned
      Adapter.UpdateCommand = UpdateCmd

      'This is the data table containing the rows you wish to update
      Dim NewRows As New DataTable("SomeTable")

      'For each modified row in NewRows, update it in the database
      Adapter.Update(NewRows)

    End Using

  End Using

End Using

上面的代码假设数据库中有一个名为yourtable的表,其中有两列col1col2是数字的。

Using块只是确保数据库对象被正确处理掉,这样就不会泄漏资源。

相关问题