读取文本文件并使用调用存储过程插入数据

时间:2013-04-03 21:17:39

标签: vb.net sql-server-2005

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

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

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

到目前为止,我有这个:

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()

1 个答案:

答案 0 :(得分: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