vb.net SqlBulkCopy 不工作,没有错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21555083/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 16:38:53  来源:igfitidea点击:

SqlBulkCopy not working, no errors

c#sqlvb.netdatatablesqlbulkcopy

提问by ZL1Corvette

I'm reading data from an Excel file or CSV. I take that data and create a datatable. I then merge that datatable with the datatable created from the original database. The merge works and I have already sorted out all of the datatypes and column names. I have a ton of links, but most of them boil down to datatype and column name/column text case.

我正在从 Excel 文件或 CSV 读取数据。我获取这些数据并创建一个数据表。然后我将该数据表与从原始数据库创建的数据表合并。合并有效,我已经整理了所有数据类型和列名。我有很多链接,但大多数都归结为数据类型和列名/列文本大小写。

No errors. Everything runs smoothly. The datatable I'm trying to bulk copy is correct in the VS table viewer. When I check in SQLExpress no changes have been made. I am using the same connection string that I have been for the rest of the project which works (row delete, add, edit, etc).

没有错误。一切顺利。我试图批量复制的数据表在 VS 表查看器中是正确的。当我签入 SQLExpress 时,没有进行任何更改。我使用的连接字符串与我用于项目其余部分的连接字符串相同(行删除、添加、编辑等)。

dt.Merge(dtnew)

    Using destinationConnection As SqlConnection = _
                   New SqlConnection(sConnectionString)
        destinationConnection.Open()

        ' Set up the bulk copy object.  
        ' The column positions in the source data reader  
        ' match the column positions in the destination table,  
        ' so there is no need to map columns. 

        Using bulkCopy As SqlBulkCopy = _
          New SqlBulkCopy(destinationConnection)
            bulkCopy.DestinationTableName = _
            "dbo.TableName"

            Try
                ' Write from the source to the destination.
                bulkCopy.WriteToServer(dt)

            Catch ex As Exception
                Console.WriteLine(ex.Message)

            Finally
                ' Close the SqlDataReader. The SqlBulkCopy 
                ' object is automatically closed at the end 
                ' of the Using block.
            End Try
        End Using

    End Using
End Sub

回答by Sarvesh Mishra

Do the column mapping also..

也做列映射..

bulkCopy.ColumnMappings.Add("source column name,"destination column name" )

or if you have same column name in dt and dbo.Tablename then you can use following code

或者如果您在 dt 和 dbo.Tablename 中有相同的列名,那么您可以使用以下代码

For Each clmn As DataColumn In dt.Columns
     bulkCopy.ColumnMappings.Add(clmn.ColumnName, clmn.ColumnName)
Next