VB.Net SQL 服务器将数据从动态数据表复制到数据库中

VB.Net SQL Server copy data from an on-the-fly-datatable into database

这是在做我的外壳......在 VB.net 2010 年和 2013 年工作。我有一个动态创建的数据table,我想将所述数据存入 table 在我的 SQL 服务器数据库中以最快的方式。目前我唯一可以开始工作的是 "insert into..." 数据中的每一行 table 通过创建 sql 将每个值插入每个字段。我想要的是 SqlServer.datatable = onTheFlyDataTable.

我逐行尝试过,但我无法让它工作,因为我用于我的服务器的 SQL table 是一个 "SELECT * FROM..." ,显然已读取只有.

我没有错误地到达 运行 的是这样的,但它从未将数据写回 SQL 服务器数据库。我 运行 没有错误,作为它结尾的 dtTEST did 包含我添加的所有行 - 它只是没有将它写回数据库。甚至尝试过 .AcceptChanges...

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

如果您只想将 DataTable 传输到数据库,则使用 SqlBulkCopy class。你会获得更好的表现。

请注意 table 结构必须相同。

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