2012-01-20 74 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