SqlBulkCopy无法正常工作,没有错误

时间:2014-02-04 14:24:07

标签: c# sql vb.net datatable sqlbulkcopy

我正在从Excel文件或CSV中读取数据。我获取数据并创建数据表。然后,我将该数据表与从原始数据库创建的数据表合并。合并工作,我已经整理出所有数据类型和列名称。我有很多链接,但大多数链接归结为数据类型和列名/列文本情况。

没有错误。一切顺利。我试图批量复制的数据表在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

1 个答案:

答案 0 :(得分:4)

列映射也是..

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

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

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