Fast SqLite data dump
Posted: Tue Jan 13, 2009 2:15 pm
Sometimes I just want to dump the contents of a table in a database and don't want to go to the trouble of writing a full blown program to do it so I tossed together a small routine for myself. Hope it helps someone.
I am sure everyone can do it better and i am used to that. PB 4.30 Final.
I am sure everyone can do it better and i am used to that. PB 4.30 Final.
Code: Select all
UseSQLiteDatabase() ; Use the SQLite database environment
Global DbHandle ; Make the database handle global
Declare FastDataExport(QueryString.s, BaseFileName.s) ; Declare the export routine so we can put it anywhere
QueryString.s = "SELECT * FROM addresses" ; Create your replaceable query string
;QueryString.s = "SELECT * FROM addresses WHERE first='John' ; Create your replaceable query string
;QueryString.s = "SELECT * FROM addresses WHERE category='fireman' ; Create your replaceable query string
BaseFileName.s = "My Address Book" ; Whatever the base export name should be
DbName.s = OpenFileRequester("Open Database", "", "SQLite database file (*.db)|*.db|All files (*.*)|*.*", 0)
If DbName.s ; Did the user choose a file or cancel?
; Open the existing database in Read Only mode
DbHandle = OpenDatabase(#PB_Any, DbName.s, "", "", #PB_Database_SQLite) ; DbHandle is checked in procedure
FastDataExport(QueryString.s, BaseFileName.s) ; Now attempt to export the data
EndIf ; No valid database name or user cancelled
End
Procedure FastDataExport(QueryString.s, TableName.s)
If DbHandle ; Was the database handle valid and not empty?
FileId = CreateFile(#PB_Any, TableName.s + "_Export.Csv") ; Try to create the file to export to in the program directory
If FileId ; Did we get a filename to open?
If DatabaseQuery(DbHandle, QueryString.s) ; Now try to run the database query passed to this procedure
NumColumns = DatabaseColumns(DbHandle) ; Get the number of columns that we have to parse
If NumColumns ; Did we get any columns returned?
While NextDatabaseRow(DbHandle) ; Now select each returned row to operate on
For NumStart = 0 To NumColumns ; Now process each column in the current row
If NumStart <> NumColumns ; Have we reached the end yet?
CurrentLine.s + Chr(34) + GetDatabaseString(DbHandle, NumStart) + Chr(34) + ","
Else ; Yes we have, leave out the final delimiter
CurrentLine.s + Chr(34) + GetDatabaseString(DbHandle, NumStart) + Chr(34)
EndIf ; Nothing else to test here
Next ; Next column to test
WriteStringN(FileId, CurrentLine.s) ; Write the current string to the opened disk file with CR/LF
CurrentLine.s = "" ; Zero the output string so we don't accumulate trash in it
Wend ; Process the next row
FinishDatabaseQuery(DbHandle) ; Flush the current query
EndIf ; We didn't get any columns in the table to process
EndIf ; The current query failed to be executed
EndIf ; We could not open or create a file to write to. Disk error?
EndIf ; Database handle empty or invalid
EndProcedure