1

我正在寻找可以将 csv 文件逐行读取然后选择选定的列和行并将它们连接到 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
4

1 回答 1

0

cmd.Parameters.Add("@Name", SqlDbType.VarChar, 50, "fileFields(3)")当您真正尝试传递实际字段时,会将“filefields(3)”作为字符串传递。当你的插入被调用时,你将不得不通过你的代码编写某种循环,然后你可以像这样插入它:

INSERT INTO Table ( Column1, Column2 ) VALUES
( Value1, Value2 ), ( Value1, Value2 ) 

您的值和列对应的位置。现在要获取 CSV,将其保存为变量(从其中包含的文本框中解析它)或从网页传回。一旦你把它拿回来,我会创建一个类来保存你的文件字段,这样你就可以稍后阅读你的代码,然后将它粘贴到一个列表中。遍历该列表并创建一个字符串。我会使用字符串生成器,因为我认为它更具可读性。然后你可以删除你的创建参数,直接调用 strSql 。这有意义吗?

如果这个答案仍然对您有帮助/您对实际代码感到好奇,请发表评论,我会写它,但由于它已经一个月大了,我假设您解决了您的问题。

于 2013-10-15T03:26:27.833 回答