我正在尝试读取.csv文件中的数据并将数据插入到mysql数据库中。 .csv文件和数据库有4列。
我可以将数据插入数据库。连接工作正常,但我无法从数据库中右侧字段的.csv文件中获取字段。
那么如何使用我正在使用的方法从数据库中相同字段的.csv文件中获取字段?
我的代码与此类似:
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("C:\ParserText.csv")
MyReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
MyReader.Delimiters = New String() {","}
Dim currentRow As String()
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
For Each currentField As String In currentRow
/*Use sql to insert data to database here*/
cmd.commandText = "INSERT INTO mydatabase(column1, column2, column3, column4) VALUES(??, ??, ??, ??)"
cmd.ExecuteNonQuery()
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & " is invalid. Skipping")
End Try
End While
End Using
答案 0 :(得分:1)
试试这段代码
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("C:\ParserText.csv")
dim table as new datatable
MyReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
MyReader.Delimiters = New String() {","}
myreader.Readline()
Do Until myreader.EndOfData = True
table.Rows.Add(myreader.ReadFields())
Loop
'Use sql to insert data to database here
for intconut=0 to table.rows.count-1
cmd.commandText = "INSERT INTO mydatabase(column1, column2, column3, column4) VALUES('" &table.rows(intcount).item(0) & "','" & table.rows(intcount).item(1) & "','" & table.rows(intcount).item(2) & "', '" & table.rows(intcount).item(3)) & "')"
cmd.ExecuteNonQuery()
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & " is invalid. Skipping")
End Try
End While
End Using
这可能会有所帮助。
答案 1 :(得分:1)
不使用sql parameterised queries。您可以更改while子句的内部以匹配以下内容:
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
cmd.commandText = string.Format("INSERT INTO mydatabase(column1, column2, column3, column4) VALUES (""{0}"", ""{1}"", ""{2}"", ""{3}"")", currentRow[0], currentRow[1], currentRow[2], currentRow[3])
cmd.ExecuteNonQuery()
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & " is invalid. Skipping")
End Try
End While
了解此代码的工作原理后,您应该将其替换为parameterised query。