这是我的外壳......在VB.net 2010和2013中工作。我有一个动态创建的数据表,我希望尽可能快地将所述数据存入我的SQL Server数据库中的表办法。目前我唯一能够工作的是“插入...”,通过创建sql将每个值插入到每个字段中。我想要的是SqlServer.datatable = onTheFlyDataTable。
我已经逐行尝试了,但我无法让它工作,因为我用于服务器表的SQL是“SELECT * FROM ...”,这显然是只读的。
我所做的运行没有错误,是这样的,但它从未将数据写回SQL Server数据库。我确实运行没有错误,dtTEST作为它的结尾做了包含我添加的所有行 - 它只是没有将它写回数据库。甚至尝试过。接受改变......
Dim sSYSsqlTEST As String = "SELECT * FROM MyDataBaseTable;"
Debug.Print(sSYSsqlTEST)
Dim cmdTEST As SqlCommand = New SqlCommand(sSYSsqlTEST, cNN)
Dim daTEST As SqlDataAdapter = New SqlDataAdapter(cmdTEST)
Dim dsTEST As DataSet = New DataSet
If Not IsNothing(daTEST) Then
daTEST.Fill(dsTEST, "TEST")
End If
Dim dtTEST As DataTable = dsTEST.Tables("TEST")
For each dr as datarow in myOnTheFlyDataTable
Dim workRow As DataRow = workTable.NewRow ()
workRow = dr
workTable.Rows.Add (workRow)
Next
我正在努力实现的目标是什么?
根据Pradeep的回复,我改变了这个但是我得到“给定的ColumnMapping与源或目标中的任何列都不匹配。 “
Using bulkCopy As SqlBulkCopy = New SqlBulkCopy(cNN)
bulkCopy.DestinationTableName = "dbo." + sCUSTOMER + "_IMPORT"
With bulkCopy.ColumnMappings
For x As Integer = 0 To iNOfields
Debug.Print("Column " + x.ToString + " Datatype = " + dtIMPORT.Columns(x).DataType.ToString)
.Add(dtIMPORT.Columns(x).ColumnName, "[FIELD " + x.ToString + "]")
Next
End With
Try
' Write from the source to the destination.
bulkCopy.WriteToServer(dtIMPORT)
Catch ex As Exception
Debug.Print(ex.Message)
Debug.Print("")
End Try
End Using
答案 0 :(得分:1)
如果您只想将DataTable
转移到数据库,请使用SqlBulkCopy
类。你会获得更好的表现。
请注意,表格结构必须相同。
Using bulkCopy As SqlBulkCopy = New SqlBulkCopy(yourConnection)
bulkCopy.DestinationTableName = "dbo.YourDataBaseTable"
With bulkCopy.ColumnMappings
.Add("srcColumn1", "destColumn1")
.Add("srcColumn2", "destColumn2")
'-- and so on ...
End With
Try
yourConnection.open()
' Write from the source to the destination.
bulkCopy.WriteToServer (myOnTheFlyDataTable)
yourConnection.Close()
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Using