【发布时间】:2014-04-09 05:12:13
【问题描述】:
我正在尝试使用 BulkUpload 将数据从 CSV 导入数据库,我能够复制 varchar 列,但在尝试导入整数列时无法导入。
错误:The given value of type String from the data source cannot be converted to type int of the specified target column.
更新
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim dt As New DataTable()
Dim line As String = Nothing
Dim i As Integer = 0
Using sr As StreamReader = File.OpenText(txtfileName.Text)
line = sr.ReadLine()
Do While line IsNot Nothing
Dim data() As String = line.Split(","c)
If data.Length > 0 Then
If i = 0 Then
If i > 4 Then
Dim column As DataColumn = New DataColumn
If i = 6 Then
column.DataType = System.Type.GetType("System.Decimal")
column.AllowDBNull = False
column.Caption = "Price"
column.ColumnName = "Price"
column.DefaultValue = 0
End If
dt.Columns.Add(column)
Else
For Each item In data
dt.Columns.Add(New DataColumn())
Next item
i += 1
End If
End If
Dim row As DataRow = dt.NewRow()
row.ItemArray = data
dt.Rows.Add(row)
End If
line = sr.ReadLine()
Loop
End Using
Using cn As New SqlConnection("Data Source=xx.xxx.in;Initial catalog=xxx;User Id=xxx;Password=xx@xx;")
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 = "tbl_Bonds"
'dt.Columns(5).DataType = GetType(Decimal)
'dt.Columns(6).DataType = GetType(Decimal)
copy.WriteToServer(dt)
End Using
End Using
End Sub
【问题讨论】:
-
第6列的数据类型是
System.Decimal还是整数?试试System.Int32。 -
我也试过了..
-
请从您的循环中删除整个数据表构建。这是错误的,并且每次迭代代码都会使情况变得更糟。建立你的数据表。一次。循环之前。废弃无用的
i变量。
标签: .net vb.net sqlbulkcopy