List of tables, db schema, dump etc using the Python sqlite3 API
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Lost Civilization
--
Chapters
00:00 Question
00:31 Accepted answer (Score 111)
01:06 Answer 2 (Score 328)
01:25 Answer 3 (Score 95)
02:03 Answer 4 (Score 36)
02:17 Thank you
--
Full question
https://stackoverflow.com/questions/3053...
Answer 1 links:
[answer]: https://stackoverflow.com/a/33100538/236...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #sqlite #dump
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Lost Civilization
--
Chapters
00:00 Question
00:31 Accepted answer (Score 111)
01:06 Answer 2 (Score 328)
01:25 Answer 3 (Score 95)
02:03 Answer 4 (Score 36)
02:17 Thank you
--
Full question
https://stackoverflow.com/questions/3053...
Answer 1 links:
[answer]: https://stackoverflow.com/a/33100538/236...
--
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;