因此,我遇到了一种情况,我使用 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 相同。这是更新数据库的代码。对于这两种情况,此代码未更改。
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", SqlDbType.Int, 1, "S_ORDER")
.InsertCommand.Parameters.Add("C_ORDER", SqlDbType.Int, 1, "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
的某种基本功能或属性?或者可能是在加载期间继承或创建的属性?难道还有什么我没想到的吗?为什么我的SqlDataAdapter
当源为DataTable
时将数据插入数据库手动创建与 DataTable
由 OleDbReader
填充?
最佳答案
每个DataTable
都会跟踪其行的RowState
,因此在循环中手动添加数据是可行的,因为它们都是Added
(它没有任何内容)手动创建DataTable
- 它的行)。当您从 Excel 等其他来源加载时,它们不会添加/新增。
如果您使用DataAdapter
来填充表格,您可以告诉它不将RowState
设置为Unchanged。这对于将数据从一个数据存储迁移到另一个数据存储非常有用:
myDA.AcceptChangesDuringFill = False
...
rows = myDA.Fill(xlDT)
关于.net - 为什么此 DataAdapter 不将行插入数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46346906/