2012-01-20 47 views
1

我有一个文本文件包含分隔记录。使用SQL数据库处理文本文件 - Visual Basic

1243;jhhf';982u4k;9u2349;huf8 
kij;9238u;98ur23;jfwf;03i24 

我需要更换与SQL数据库(Select X from T where C='4Th part from the flatfile')的返回值的每个记录的第四部分的价值。

Regards,
SAnthosh。

+0

注意,我的答案的一部分是从我以前的答案采取在术后第http://stackoverflow.com/questions/8922426/text-file-handling-in-visual-基本/ 8922498#8922498 – Marco

回答

1

试试这个:

Dim newLines As List(Of String) = New List(Of String) 
Dim sqlConn As New SqlConnection(connectionString) 
Dim SQLCmd As New SqlCommand() 
SQLCmd.Connection = sqlConn 
Dim lines As String() = File.ReadAllLines(filename) 
sqlConn.Open() 
For Each line As String In lines 
    Dim parts As String() = line.Split(";") 
    SQLCmd.CommandText = "Select X from T where C=""" & parts(3) & """" 
    Dim dr As SqlDataReader = SQLCmd.ExecuteReader 
    While dr.Read() 
     parts(3) = dr("X") 
    End While 
    newLines.Add(String.Join(";", parts)) 
Next 
File.WriteAllLines(filename, newLines.ToArray()) 
sqlConn.Close() 
+0

@ user1157902:你试过我的代码吗?这是你需要的吗? – Marco

+0

System.IndexOutOfRangeException未处理 Message =“索引超出了数组的范围。” –

+0

@ user1157902:这意味着'line.Split'返回的小于4个部分,因此您的文件不是您所描述的方式,我认为.... – Marco