我正在寻找可以将csv文件逐行读取然后选择coluns和行并将它们连接到mysql数据库的方法。
我已经制作了以下代码但是我无法将其连接到sql数据库中插入。
如何使用Columns Time,Name,Location all varchars将其连接到我的数据库?
Imports System.IO
Imports System.IO
Imports System.Data.SqlClient
Public Class Form4
Dim con As New SqlConnection
Dim com As New SqlCommand
Dim str As String
Public Sub ReadCSVFile()
Dim fileIn As String = "C:\Users\FFFF\Downloads\new.csv"
Dim fileRows(), fileFields() As String
TextBox1.Text = String.Empty
If File.Exists(fileIn) Then
Dim fileStream As StreamReader = File.OpenText(fileIn)
fileRows = fileStream.ReadToEnd().Split(Environment.NewLine)
For i As Integer = 0 To fileRows.Length - 1
fileFields = fileRows(i).Split(",")
If fileFields.Length >= 4 Then
TextBox1.Text += fileFields(3) & " " & fileFields(2) & " " & fileFields(0) & "<br /> "
End If
Next
Else
TextBox1.Text = fileIn & " not found."
End If
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Call ReadCSVFile()
End Sub
Private Sub Form4_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
con = New SqlConnection("Data Source=FFF-PC;Initial Catalog=MySolution;User Id=sa;Password=sarfar.811;")
Dim cmd As New SqlCommand()
cmd.CommandType = CommandType.Text
cmd.Connection = con
cmd.Parameters.Add("@Name", SqlDbType.VarChar, 50, "fileFields(3)")
cmd.Parameters.Add("@Time", SqlDbType.VarChar, 20, "fileFields(2)")
cmd.Parameters.Add("@Location", SqlDbType.VarChar, 50, "fileFields(0)")
Dim strSql As String = "Insert into New_1(Name,Time,Location) values(@Name@Time,@Location)"
Dim dAdapter As New SqlDataAdapter()
dAdapter.InsertCommand = cmd
'Dim result As Integer = dAdapter.Update(ReadingCsv)
End Sub
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
End Sub
End Class
答案 0 :(得分:0)
cmd.Parameters.Add("@Name", SqlDbType.VarChar, 50, "fileFields(3)")
会将“filefields(3)”作为字符串传递。当你的插入被调用时,你将不得不在代码中编写某种循环,然后你可以插入它:
INSERT INTO Table ( Column1, Column2 ) VALUES
( Value1, Value2 ), ( Value1, Value2 )
您的值和列对应的位置。现在获取CSV,将其保存为变量(从包含在其中的文本框中解析)或从网页传回。一旦你有了它,我会创建一个包含你的文件字段的类,这样你可以稍后阅读你的代码,然后将其粘贴到列表中。遍历该列表并创建一个字符串。我使用字符串生成器因为我认为它更具可读性。然后你可以删除你的创建参数,直接调用strSql。这有意义吗?
如果这个答案仍然可以帮助你/你对实际的代码感到好奇,那么我会写下它,但是因为它已经有一个月了,我假设你已经解决了问题。