【发布时间】:2012-07-01 08:21:52
【问题描述】:
VB2010 我有一个 DataSet,我添加了多个表,然后我填写这些表,然后将这些记录插入 Access db。
'create a new DataSet
Dim dsNav As New DataSet
'first table
Dim daTrips As New OleDb.OleDbDataAdapter("SELECT * FROM Trips", connNav)
daTrips.Fill(dsNav, "Trips")
Dim cbTrips As New OleDb.OleDbCommandBuilder(daTrips)
'second table
Dim daCars = New OleDb.OleDbDataAdapter("SELECT * FROM Cars", connNavDb)
daCars.Fill(dsNav, "Cars")
Dim cbCars As New OleDb.OleDbCommandBuilder(daCars)
'here i open a huge text file and depending on the data i encounter, I create
'a new DataRow and add it to the appropriate table. i add many new rows to each
'table. for example
Dim dsNewRow As DataRow = {tblCars}.NewRow()
dsNewRow.Item("CarId") = textline.Substring(0, 10)
dsNewRow.Item("CarMake") = textline.Substring(11, 15)
tblCars.Rows.Add(dsNewRow)
'i finish reading the text file and filling up the tables in the one DataSet
'now i want to insert those records into the Access db
Dim rowCnt1 As Integer = daTrips.Update(dsNav, "Trips")
Dim rowCnt2 As Integer = daCars.Update(dsNav, "Cars")
第一次更新有效,但在第二次更新时出现异常:
在 System.Data.dll 中发生了“System.Data.OleDb.OleDbException”类型的第一次机会异常 System.Data.OleDb.OleDbException (0x80040E14):INSERT INTO 语句中的语法错误。 在 System.Data.Common.DbDataAdapter.UpdatedRowStatusErrors(RowUpdatedEventArgs rowUpdatedEvent,BatchCommandInfo[] batchCommands,Int32 commandCount) 在 System.Data.Common.DbDataAdapter.UpdatedRowStatus(RowUpdatedEventArgs rowUpdatedEvent,BatchCommandInfo[] batchCommands,Int32 commandCount) 在 System.Data.Common.DbDataAdapter.Update(DataRow[] dataRows,DataTableMapping tableMapping) 在 System.Data.Common.DbDataAdapter.UpdateFromDataTable(DataTable 数据表,DataTableMapping 表映射) 在 System.Data.Common.DbDataAdapter.Update(DataSet dataSet, String srcTable)
我看过各种文章,他们都建议用一个包含多个 DataTables 的 DataSet 来更新数据库是可行的,但就是不知道为什么会这样。
【问题讨论】:
-
很难说发生了什么。我将尝试查看 daCars 适配器上插入命令的命令文本是什么。
daCars.InsertCommand.CommandText -
所以我在 daTrips.Update 之前添加了一个调试 Debug.Print(daTrips.InsertCommand.CommandText),它抛出了一个异常 System.NullReferenceException。与 UpdateCommand 相同。我根本没有设置这些。我以为 OleDbCommandBuilder 会为您设置这些。
-
Cars 表只包含上面两个字段还是有其他字段?如果存在,您能否显示这些其他字段的名称?
-
另外,试试这个 -
daCars.InsertCommand = cbCars.GetInsertCommand();然后看看 InsertCommand.CommandText -
再一次,Cars 表定义了主键?如果您希望 commandbuilder 使用更新,表必须有一个主键。
标签: vb.net ms-access datatable dataset oledb