vb.net sql bulkcopy非字符串值问题

时间:2016-10-08 05:10:03

标签: vb.net

我可以使用sqlbulkcopy将csv文件中的非字符串值插入到sql表中吗?

我有以下代码来创建数据表:

     Dim dt As New DataTable()
    Dim line As String = Nothing
    Dim i As Integer = 0

    Using sr As StreamReader = File.OpenText("C:\Users\Administrator\Desktop\Sked Lente\Data\wingrd13.csv")
        line = sr.ReadLine()
        Do While line IsNot Nothing
            Dim data() As String = line.Split(","c)
            If data.Length > 0 Then
                If i = 0 Then
                    For Each item In data
                        dt.Columns.Add(New DataColumn())
                    Next item
                    i += 1
                End If
                Dim row As DataRow = dt.NewRow()
                row.ItemArray = data
                dt.Rows.Add(row)
            End If
            line = sr.ReadLine()
        Loop
    End Using

我还有以下代码用于sqlbulkcopy:

        Using cn As New SqlConnection(ConfigurationManager.ConnectionStrings("SQLConnStr").ConnectionString)
        cn.Open()
        Using copy As New SqlBulkCopy(cn)
            copy.ColumnMappings.Add(0, 0)
            copy.ColumnMappings.Add(1, 1)
            copy.ColumnMappings.Add(2, 2)
            copy.ColumnMappings.Add(3, 3)
            copy.ColumnMappings.Add(4, 4)
            copy.ColumnMappings.Add(5, 5)
            copy.ColumnMappings.Add(6, 6)
            copy.DestinationTableName = "wingrd13"
            copy.WriteToServer(dt)
        End Using
    End Using

我在该行收到错误:copy.ColumnMappings.Add(6,6)

我的数据库中的列是真实的。

此致

1 个答案:

答案 0 :(得分:0)

SqlBulkCopy会插入您DataTable的数据,因此,如果您要插入非文字数据,那么您的DataTable必须包含非文字数据。在将数据添加到DataTable之前,您有责任将从CSV文件中读取的数据转换为适当的数据类型。转换不会自动发生。