List of tables, db schema, dump etc using the Python sqlite3 API
--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Book End
--
Chapters
00:00 List Of Tables, Db Schema, Dump Etc Using The Python Sqlite3 Api
00:22 Answer 1 Score 340
00:39 Accepted Answer Score 111
00:59 Answer 3 Score 96
01:27 Answer 4 Score 37
01:38 Answer 5 Score 29
02:28 Thank you
--
Full question
https://stackoverflow.com/questions/3053...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #sqlite #dump
#avk47
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Book End
--
Chapters
00:00 List Of Tables, Db Schema, Dump Etc Using The Python Sqlite3 Api
00:22 Answer 1 Score 340
00:39 Accepted Answer Score 111
00:59 Answer 3 Score 96
01:27 Answer 4 Score 37
01:38 Answer 5 Score 29
02:28 Thank you
--
Full question
https://stackoverflow.com/questions/3053...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #sqlite #dump
#avk47
ANSWER 1
Score 345
In Python:
import sqlit3
con = sqlite3.connect('database.db')
cursor = con.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
print(cursor.fetchall())
Watch out for my other answer. There is a much faster way using pandas.
ACCEPTED ANSWER
Score 112
You can fetch the list of tables and schemata by querying the SQLITE_MASTER table:
sqlite> .tab
job snmptarget t1 t2 t3
sqlite> select name from sqlite_master where type = 'table';
job
t1
t2
snmptarget
t3
sqlite> .schema job
CREATE TABLE job (
id INTEGER PRIMARY KEY,
data VARCHAR
);
sqlite> select sql from sqlite_master where type = 'table' and name = 'job';
CREATE TABLE job (
id INTEGER PRIMARY KEY,
data VARCHAR
)
ANSWER 3
Score 96
The FASTEST way of doing this in python is using Pandas (version 0.16 and up).
Dump one table:
db = sqlite3.connect('database.db')
table = pd.read_sql_query("SELECT * from table_name", db)
table.to_csv(table_name + '.csv', index_label='index')
Dump all tables:
import sqlite3
import pandas as pd
def to_csv():
db = sqlite3.connect('database.db')
cursor = db.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
tables = cursor.fetchall()
for table_name in tables:
table_name = table_name[0]
table = pd.read_sql_query("SELECT * from %s" % table_name, db)
table.to_csv(table_name + '.csv', index_label='index')
cursor.close()
db.close()
ANSWER 4
Score 37
I'm not familiar with the Python API but you can always use
SELECT * FROM sqlite_master;