Skip to content

Instantly share code, notes, and snippets.

@ajmcdaniel
Created April 13, 2012 02:03
Show Gist options
  • Save ajmcdaniel/2372930 to your computer and use it in GitHub Desktop.
Save ajmcdaniel/2372930 to your computer and use it in GitHub Desktop.
Snippet to dump and load zipped sqlite3 databases, based on Eli Bendersky's example. Useful for storing sqlite3 databases from memory to disk
import zipfile
def dump_database(connection, dump_file, sql_file):
"""Function to dump sqlite3 database into zipped file
see: http://bit.ly/IAUmKc
python 2.6+ only
connection: sqlite3 database connection
dumpfile: the name of the zipfile to store the sql_file info
[remember to add a .zip extension]
sql_file: The name of the sql file to dump the database info into
[remember to add a .sql extension]
"""
# Open the db and dump all its data into the 'data' buffer
sql_dump = ''.join([data.encode('ISO-8859-1') for data in connection.iterdump()])
# Create a zip file and write add the dump into it as a new file
zf = zipfile.ZipFile(dump_file, mode='w', compression=zipfile.ZIP_DEFLATED)
zf.writestr(sql_file, sql_dump )
zf.close()
def load_database(zip_file, sql_file):
"""Returns a list of sql statements used to recreate a dumped database"""
zf = zipfile.ZipFile(zip_file)
try:
data = zf.read(sql_file)
# break sql into readable statements and re-create creation statements
# return data # uncomment for return of raw sql data
return data.split(';')
except KeyError:
print '%s not found in zip file' % (sql_file,)
if __name__ == '__main__':
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment