我正在使用vb.net将csv数据导入sql server表,如果csv中的所有单元格都具有正确的值,则一切正常,但错误发生为“无法将参数值从字符串转换为Double”。一旦浮点数在csv中有空单元格。有没有人经历过这个?能建议我吗?我的代码是:
Dim table As New DataTable()
Dim parser As New FileIO.TextFieldParser("D:\test_1.csv")
table.Columns.Add("OBJECTID")
table.Columns.Add("FIELD1")
table.Columns.Add("FIELD2")
table.Columns.Add("FIELD3")
table.Columns.Add("FIELD4")
table.Columns.Add("FIELD5")
table.Columns.Add("FIELD6")
table.Columns.Add("FIELD7")
table.Columns.Add("FIELD8")
table.Columns.Add("FIELD9")
parser.Delimiters = New String() {","}
parser.HasFieldsEnclosedInQuotes = True
parser.TrimWhiteSpace = True
parser.ReadLine()
Do Until parser.EndOfData = True
table.Rows.Add(parser.ReadFields())
Loop
Dim strSql As String = "INSERT INTO BQInfoTest (OBJECTID, FIELD1, FIELD2, FIELD3, FIELD4, FIELD5, FIELD6, FIELD7, FIELD8, FIELD9) VALUES (@OBJECTID, @FIELD1, @FIELD2, @FIELD3, @FIELD4, @FIELD5, @FIELD6,@FIELD7,@FIELD8, @FIELD9)"
Using SqlconnectionString As New SqlConnection("Server=PC- 36\TESTDB;Database=test_db;User Id=testuser;Password=testuser;")
Dim cmd As New SqlClient.SqlCommand(strSql, SqlconnectionString)
With cmd.Parameters
.Add("@OBJECTID", SqlDbType.Int, 8, "OBJECTID")
.Add("@FIELD1", SqlDbType.VarChar, 15, "FIELD1")
.Add("@FIELD2", SqlDbType.VarChar, 200, "FIELD2")
.Add("@FIELD3", SqlDbType.VarChar, 20, "FIELD3")
.Add("@FIELD4", SqlDbType.Int, 8, "FIELD4")
.Add("@FIELD5", SqlDbType.Date, 20, "FIELD5")
.Add("@FIELD6", SqlDbType.Date, 20, "FIELD6")
.Add("@FIELD7", SqlDbType.Date, 20, "FIELD7")
.Add("@FIELD8", SqlDbType.Float, 8, "FIELD8")
.Add("@FIELD9", SqlDbType.Float, 8, "FIELD9")
End With
Dim adapter As New SqlClient.SqlDataAdapter()
adapter.InsertCommand = cmd
Dim iRowsInserted As Int32 = adapter.Update(table)
End Using
由于数据库中的某些字段允许为null,因此csv中的某些数据为空。我想知道如何处理空单元格?
答案 0 :(得分:2)
你应该尝试这样:(未经测试的代码给你一个想法)
Do Until parser.EndOfData = True
dim data as string() = parser.ReadFields()
for i as integer = 0 to data.Length - 1
if(string.isNullOrEmpty(data(i))) then
data(i) = DBNull.Value ' <-------- Here you go
end if
next
table.Rows.Add(data)
Loop
希望它有所帮助!