Сообщение об ошибке, которое вы упомянули, не имеет ничего общего с первичными ключами таблицы, которую вы пытаетесь обновить, вместо этого оно жалуется, потому что вы не дали адаптеру правильную команду, которую он может использовать для обновления базовой таблицы.
Вы столкнетесь с той же ошибкой, если попытаетесь вставить или удалить новые строки без указания команды вставки или удаления на адаптере.
Чтобы решить эту проблему, инициализируйте ваше свойство 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
с двумя столбцами col1
и col2
, которые являются числовыми.
Блоки Using
просто обеспечивают правильное удаление объектов базы данных, чтобы не допустить утечки ресурсов.