Thursday, November 17, 2011

Running multiple SQL commands from the dump file (UTF8 compatible) in MSAccess

I had a hard time running multiple UPDATE commands on an MSAccess database. Even the latest version choke on the following error.



The next logical step for every PHP programmer is to run multiple VBA commands each running a single SQL UPDATE command. Guess what? It works, but VBA doesn't support UTF8 in the queries.

Sub import()
CurrentDb.execute "UPDATE item SET translation = 'привет', pronounce = '' WHERE id = 122"
 CurrentDb.execute "UPDATE item SET translation = 'VBA сакс', pronounce = '' WHERE id = 123"
End Sub

Attempt #3. Read SQL dump from UTF8 file and run each line as SQL command. I found the following code and it doesn't support UTF8 either.


Sub import_file()
    Set FSO = CreateObject("Scripting.FileSystemObject")
    Dim oFS
    
    Set oFS = FSO.OpenTextFile("c:\users\...\desktop\Import.txt")
    
    Do Until oFS.AtEndOfStream
        sText = oFS.ReadLine
        CurrentDb.execute sText
    Loop
End Sub


Only on fourth attempt I have found a way to read UTF8 data from the file. Executing queries in this way actually works. Spend four hours on this research. Hope it helps.



Sub import_file_utf8()
    Dim File ' As ADODB.Stream
    Set File = CreateObject("ADODB.Stream")
    File.Open
    File.Type = 2
    File.Charset = "UTF-8"
    File.LoadFromFile "c:\users\...\desktop\Import.txt"
    Do Until File.eos
        myString = File.ReadText(-2)
        Debug.Print myString
        CurrentDb.execute myString
    Loop
    File.Close
End Sub

No comments: