I would like to dump only one table but by the looks of it, there is no parameter for this.
I found this example of the dump but it is for all the tables in the DB:
# Convert file existing_db.db to SQL dump file dump.sql
import sqlite3, oscon = sqlite3.connect('existing_db.db')
with open('dump.sql', 'w') as f:for line in con.iterdump():f.write('%s\n' % line)
You can copy only the single table in an in memory db:
import sqlite3def getTableDump(db_file, table_to_dump):conn = sqlite3.connect(':memory:') cu = conn.cursor()cu.execute("attach database '" + db_file + "' as attached_db")cu.execute("select sql from attached_db.sqlite_master ""where type='table' and name='" + table_to_dump + "'")sql_create_table = cu.fetchone()[0]cu.execute(sql_create_table);cu.execute("insert into " + table_to_dump +" select * from attached_db." + table_to_dump)conn.commit()cu.execute("detach database attached_db")return "\n".join(conn.iterdump())TABLE_TO_DUMP = 'table_to_dump'
DB_FILE = 'db_file'print getTableDump(DB_FILE, TABLE_TO_DUMP)
Pro:
Simplicity and reliability: you don't have to re-write any library method, and you are more assured that the code is compatible with future versions of the sqlite3 module.
Con:
You need to load the whole table in memory, which may or may not be a big deal depending on how big the table is, and how much memory is available.