使用SqlBulkCopy插入SQL

时间:2014-10-29 18:20:34

标签: sql-server vb.net sqlbulkcopy

我不知道为什么数据没有进入SQL。有人可以查看这个,看看我的代码有什么问题吗?我从MSDN页面获得了下面的大部分代码:http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy(v=vs.110).aspx

Dim connectionString As String = "Server= "<servername>"; integrated security=true"

    Using sourceConnection As SqlConnection = _

        New SqlConnection(connectionString)
        sourceConnection.Open()

        Dim commandSourceData As SqlCommand = New SqlCommand(<TSQL>), sourceConnection)
        Dim reader As SqlDataReader = commandSourceData.ExecuteReader

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

            Using bulkcopy As SqlBulkCopy = _
                New SqlBulkCopy(destinationConnection)
                bulkcopy.DestinationTableName = _
                    "<tableName>"

                Try
                    bulkcopy.WriteToServer(reader)
                Catch ex As Exception
                    Console.WriteLine(ex.Message)
                Finally
                    reader.Close()
                End Try

            End Using
        End Using
        sourceConnection.Close()
    End Using

2 个答案:

答案 0 :(得分:3)

在我执行BulkCopy的系统中,我按照文档Column Mapping - SQL Bulk Copy

中的说明设置了列映射。

使用源列和目标列名设置映射。此示例来自文档:

 Dim mapID As New _
              SqlBulkCopyColumnMapping("ProductID", "ProdID")
            bulkCopy.ColumnMappings.Add(mapID)

当我第一次设置它时,我记得在没有明确设置环境中的列映射的情况下遇到麻烦。

答案 1 :(得分:1)

如果数据源的字段类型,字段顺序,字段数与目标表不同。您的批量复制将返回失败。

在上面的例子中,您应该将datasoruce中每个字段的ColumnMappings指定为sqlbulkcopy对象。

            SqlBulkCopy copy = new SqlBulkCopy(MySqlConn);
            copy.BulkCopyTimeout = 6000;
            copy.DestinationTableName = TableName;
            for (int i = 0; i < this.lstBulkFields.Count; i++) {
                // if the source fields name are the same with the targets.
                copy.ColumnMappings.Add(this.lstBulkFields[i], this.lstBulkFields[i]);
            }
            copy.BatchSize = BatchSize;
            copy.WriteToServer(MyDataSource);