0

我需要读取逗号分隔的数据文件:

a,123,C:/test.txt,0001

我需要将它们读入数组,然后使用调用方法来调用存储过程。然后,这将从文本文件中获取数据,然后放入表中的列中。

到目前为止我有这个:

Dim path As String
path = "C:\Users\dave\Desktop\WF.txt"

Dim sr As StreamReader = New StreamReader(path)

Dim line As String
line = ""

' Split(
Do
  Try
    line = sr.ReadLine()
    Console.WriteLine(line)
  Catch ex As Exception
    Console.WriteLine("the file could not be read:")
    Console.WriteLine(ex.Message)
  End Try
Loop Until line Is Nothing

sr.Close()
4

1 回答 1

1

我会尝试这样的事情:

Dim path As String = "C:\Users\dave\Desktop\WF.txt"
Dim line As String = String.Empty

' define connection string and stored procedure name 
Dim connectionString As String = "server=.;database=test;integrated Security=SSPI;"
Dim storedProcedureName As String = "dbo.YourInsertStoredProcedure"

' put all disposable items in using() blocks - this applies to 
' StreamReader, SqlConnection, SqlCommand (and many more!)
Using sr As New StreamReader(path)
    Using conn As New SqlConnection(connectionString)
        Using cmd As New SqlCommand(storedProcedureName, conn)
            ' define as stored procedure
            cmd.CommandType = CommandType.StoredProcedure

            ' define parameters
            cmd.Parameters.Add("@Param1", SqlDbType.VarChar, 10)
            cmd.Parameters.Add("@Param2", SqlDbType.Int)
            cmd.Parameters.Add("@Param3", SqlDbType.VarChar, 260)
            cmd.Parameters.Add("@Param4", SqlDbType.VarChar, 25)

            Do
                Try
                    line = sr.ReadLine()

                    If Not String.IsNullOrEmpty(line) Then
                        ' split line into the four parts
                        Dim parts As String() = line.Split(",")

                        ' set the parameter values
                        cmd.Parameters("@Param1").Value = parts(0)
                        cmd.Parameters("@Param2").Value = Convert.ToInt32(parts(1))
                        cmd.Parameters("@Param3").Value = parts(2)
                        cmd.Parameters("@Param4").Value = parts(3)

                        ' execute procedure
                        cmd.ExecuteNonQuery()
                    End If
                Catch ex As Exception
                    Console.WriteLine("the file could not be read:")
                    Console.WriteLine(ex.Message)
                End Try
            Loop While Not String.IsNullOrEmpty(line)
        End Using
    End Using
End Using
于 2013-04-04T14:02:36.383 回答