如何在ExecuteReader循环中运行Sqlite Update Query

时间:2016-02-22 07:55:23

标签: vb.net sqlite

我在sqlite(vb.net)中有一个独特的情况,我试图在循环时在ExecuteReader中更新文件。

场景:db表列:ID,Val1,Val2 输入:有2个字符数组。 任务:

 to update ALL ROWS:
 1. Read VAL1  
 2. Replace CHARACTERS as defined in strMapp e.g. (A->a,B->x,D->f) etc
 3. UPDATE this new String to column 'Val2'

我的代码很远:

dim strMap As New Dictionary(Of String, String)
strMap.Add("A", "a")
strMap.Add("B", "x")
strMap.Add("C", "f")
strMap.Add("D", "h")
strMap.Add("E", "l")    
conn1 = New SQLiteConnection("Data Source=test.s3db;Read Only=True")
conn2 = New SQLiteConnection("Data Source=test.s3db")
Dim cmd As New SQLiteCommand(conn1)
Dim cmd2 As New SQLiteCommand(conn2)
conn1.open  ''read only
conn2.open  ''to update
Dim ii As Integer
Dim query as String = "SELECT ID,Val1,Val2 FROM my_table"
cmd.commandText=query
Dim myReader As SQLiteDataReader

myReader = cmd.ExecuteReader

If myReader.HasRows = True Then
    Do While myReader.Read()
        oldStr = myReader("Val1")
        newStr = oldStr
        For j As Integer = 0 To newStr .Length - 1
            nChar = newStr.Substring(j, 1)
            If strMap.ContainsKey(nChar) Then
                newStr = newStr .Replace(nChar, strMap(nChar))
            End If
        Next j
        Qry = "UPDATE my_table set Val2='" & newStr "' WHERE ID=" & myReader("ID")
        cmd2.CommandText=Qry
        cmd2.ExecuteNonQuery(Qry) '''''THIS CODE GIVES ERROR: database corruption
        ii = ii + 1
    Loop
End If

问题:它给出了“数据库损坏”错误。我已经标记了发生错误的代码。请指教

1 个答案:

答案 0 :(得分:0)

好的,似乎在datareader打开并处于活动状态时我无法更新数据库。所以,我采用了一种不同的方法来实现这一点,首先将记录存储在DataSet中,然后再执行UPDATE部分。因此我一起避免使用DataReader。这是我的新工作代码:)它也可以被理解为如何避免SQLiteDataReader:)

dim strMap As New Dictionary(Of String, String)
strMap.Add("A", "a")
strMap.Add("B", "x")
strMap.Add("C", "f")
strMap.Add("D", "h")
strMap.Add("E", "l")    

    Dim DS As New DataSet
    Dim DT As New DataTable
    Dim cmd As New SQLiteCommand
    Dim query As String = "SELECT ID,Val1,Val2 FROM my_table"
    Dim DB As New SQLiteDataAdapter(query, connection)
    DS.Reset()
    DB.Fill(DS)
    DT = DS.Tables(0)
    cmd.Connection = connection
    Dim nStr, oStr, Qry As String
    Dim nChar, oChar As String
    For Each row As DataRow In DT.Rows
        oStr = row("FirstLetterStr")
        nStr = ""
        For j As Integer = 0 To oStr.Length - 1
            oChar = oStr.Substring(j, 1)
            If strMap.ContainsKey(oChar) Then
                nChar = strMap(oChar)
                nStr += nChar
            End If
        Next j
        Qry = "UPDATE my_table set Val2='" & nStr & "' WHERE ID=" & row("ID")
        cmd.CommandText = Qry
        cmd.ExecuteNonQuery()
    Next row