我正在尝试从 .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
最佳答案
试试这个代码
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
这可能会有所帮助。
关于mysql - TextFieldParser 读取文件并插入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29558454/