2013-04-03 45 views
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() 
+0

而** **该数据库是本作?调用存储过程对于您正在使用的数据库系统非常具体。 – 2013-04-04 05:10:24

+0

我有我的文本文件像上面显示我需要从文本文件插入到sql服务器数据库05这个数据,有一个插入存储过程创建。逗号后的每个数据将使用vb.net中的存储过程到不同的字段。 – kenmru 2013-04-04 13:47:04

+0

我需要使用vb.net将文本文件中的数组传递给存储过程。 数据在文本文件上以逗号分隔 – kenmru 2013-04-04 13:50:12

回答

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 
+0

谢谢Marc,这很接近我试图做的事情...... GOd祝福 – kenmru 2013-04-04 17:03:38

+0

如果我必须做同样的事情,但我的读者在特定列中逐行阅读然后使用相同的存储过程 – kenmru 2013-04-14 18:15:46

+0

如果我必须做同样的事情,但我的阅读器在特定列中逐行读取,然后使用相同的存储过程 – kenmru 2013-04-14 18:16:19

相关问题