所以我有一种情况,我使用sqlDataAdapter将行插入sql Server 2014数据库中的表.
数据来源是Excel电子表格.
使用一些For循环和.Columns.Add和.Rows.Add填充DataTable对象以从Excel工作表复制数据时,插入工作正常.这个工作代码我没有包含在这里.
但是,我正在重构代码以使用OleDbDataReader.这是我的功能:
Private Function FillDataTable(path As String,name As String) As DataTable Dim fullpath As String = path Dim wsname As String = name Dim dt = New DataTable() Try Dim connectionstring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & fullpath & "';Extended Properties= 'Excel 8.0;HDR=Yes;IMEX=1'" Dim commandstring As String = "Select * From " & wsname Using con As New OleDbConnection(connectionstring) Using cmd As New OleDbCommand(commandstring,con) con.Open() Using dr As OleDbDataReader = cmd.ExecuteReader() With dt For Each c In aryFieldList .Columns.Add(c.FieldName,ConvertType(c.DataType)) Next .Columns.Add("SubmID") .Columns("SubmID").DefaultValue = 0 .Columns.Add("S_ORDER") .Columns("S_ORDER").DefaultValue = 0 .Columns.Add("C_ORDER") .Columns("C_ORDER").DefaultValue = 0 End With dt.Load(dr) End Using End Using End Using Catch ex As Exception MsgBox(ex.Message) End Try Return dt End Function
当我调试时,从函数返回的DataTable包含集合中的数据,否则看起来与先前版本的代码中的DataTable相同.以下是.Update数据库的代码.这两种情况的代码都没有变化.
Dim dt = New DataTable() dt = FillDataTable(fullpath,wsname) Using cn = New sqlConnection(ConfigurationManager.ConnectionStrings("Connection").ConnectionString) cn.Open() Using adp = New sqlDataAdapter() Dim sb As New StringBuilder [...StringBuilder code to build the Insert command here...] Dim cmd As New sqlCommand(sb.ToString,cn) With adp .InsertCommand = cmd .InsertCommand.Parameters.Add("SubmID",sqlDbType.Int,1,"SubmID") .InsertCommand.Parameters.Add("S_ORDER","S_ORDER") .InsertCommand.Parameters.Add("C_ORDER","C_ORDER") For Each p In aryFieldList If p.Excluded = False Then .InsertCommand.Parameters.Add(p.FieldName,p.DataType,p.Length,p.FieldName) End If Next adp.Update(dt) End With 'adp End Using 'adp End Using 'cn
没有例外被抛出.调试adp.Update(dt)行没有延迟,就好像查询根本没有执行一样.这是我注意到行/列添加DT和OleDB填充DT之间的唯一区别 – 成功插入数据时有一点延迟时间.
我是否遗漏了DataTable的某些基本功能或属性,或者是在Load期间继承或创建的属性?这是我还没有想到的其他事情吗?当源是手动创建的DataTable而不是OleDbReader填充的DataTable时,为什么我的sqlDataAdapter将数据插入数据库?