205

For some reason I can't find a way to get the equivalents of sqlite's interactive shell commands:

.tables
.dump

using the Python sqlite3 API.

Is there anything like that?

General Grievance
  • 4,555
  • 31
  • 31
  • 45
noamtm
  • 12,435
  • 15
  • 71
  • 107
  • 1
    I suggest renaming the question to something non python specific since the answer is actually universal to interfaces that use SQL. – unode Nov 11 '10 at 16:34
  • 2
    True, although I was expecting a python API when asking it. I'll try to find the right name. – noamtm Nov 15 '10 at 08:54
  • 3
    If wanting to show tables from the sqlite3 command prompt, refer to http://stackoverflow.com/questions/82875/how-do-i-list-the-tables-in-a-sqlite-database-file. If using Python package sqlite3, see Davoud Taghawi-Nejad's answer here. I suggest the OP add Python back into the question title and select Davoud's answer. I found this page by googling "show tables Python sqlite3" since Google knows the old question title. Searches within SO would fail to land here. Without the Python angle, the linked duplicate question 82875 has received far more crowd wisdom. – Bennett Brown Dec 07 '14 at 17:13

12 Answers12

332

In Python:

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.

Community
  • 1
  • 1
Davoud Taghawi-Nejad
  • 16,142
  • 12
  • 62
  • 82
111

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
)
converter42
  • 7,400
  • 2
  • 29
  • 24
  • 2
    `sqlite> .schema job` invalid syntax in python...what am I missing? – jbuddy_13 Apr 23 '20 at 15:34
  • 1
    @jbuddy_13 see the [other answer](https://stackoverflow.com/a/10746045/5049813) – Pro Q May 24 '20 at 05:50
  • 1
    @jbuddy_13 `sqlite>` is the sqlite command line client prompt. The purpose of the example was to demonstrate how one could query the database to list tables and schema. – converter42 May 25 '20 at 16:11
  • 15
    sorry but i really dont know why this is the accepted answer, the question is specific for python not SQL language – Kostas Markakis Nov 02 '20 at 08:53
  • @KostasMarkakis is it really that difficult to imagine how the information I listed might lead to a solution using the API? – converter42 Feb 15 '21 at 17:02
  • Remark on the name of the "db schema": (at present time!) should be `sqlite_schema` and `sqlite_master` is kept for _"historical compatibility"_, see [doc](https://www.sqlite.org/schematab.html) – cards May 19 '22 at 07:53
95

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()
lesolorzanov
  • 3,536
  • 8
  • 35
  • 53
Davoud Taghawi-Nejad
  • 16,142
  • 12
  • 62
  • 82
  • 5
    For users coming to copy/paste: Be sure to `cursor.close()` and `db.close()`. – T.Woody Dec 08 '18 at 19:31
  • 11
    or better use `with sqlite3.connect('database.db') as db:` – frans Jul 16 '19 at 05:31
  • How come you are using pandas and "shortcutting" the cursor? Aren't we supposed to use the cursor for querying the database?!! – Ash Aug 01 '23 at 16:18
37

I'm not familiar with the Python API but you can always use

SELECT * FROM sqlite_master;
finnw
  • 47,861
  • 24
  • 143
  • 221
28

Here's a short and simple python program to print out the table names and the column names for those tables (python 2. python 3 follows).

import sqlite3

db_filename = 'database.sqlite'
newline_indent = '\n   '

db=sqlite3.connect(db_filename)
db.text_factory = str
cur = db.cursor()

result = cur.execute("SELECT name FROM sqlite_master WHERE type='table';").fetchall()
table_names = sorted(zip(*result)[0])
print "\ntables are:"+newline_indent+newline_indent.join(table_names)

for table_name in table_names:
    result = cur.execute("PRAGMA table_info('%s')" % table_name).fetchall()
    column_names = zip(*result)[1]
    print ("\ncolumn names for %s:" % table_name)+newline_indent+(newline_indent.join(column_names))

db.close()
print "\nexiting."

(EDIT: I have been getting periodic vote-ups on this, so here is the python3 version for people who are finding this answer)

import sqlite3

db_filename = 'database.sqlite'
newline_indent = '\n   '

db=sqlite3.connect(db_filename)
db.text_factory = str
cur = db.cursor()

result = cur.execute("SELECT name FROM sqlite_master WHERE type='table';").fetchall()
table_names = sorted(list(zip(*result))[0])
print ("\ntables are:"+newline_indent+newline_indent.join(table_names))

for table_name in table_names:
    result = cur.execute("PRAGMA table_info('%s')" % table_name).fetchall()
    column_names = list(zip(*result))[1]
    print (("\ncolumn names for %s:" % table_name)
           +newline_indent
           +(newline_indent.join(column_names)))

db.close()
print ("\nexiting.")
RufusVS
  • 4,008
  • 3
  • 29
  • 40
26

If someone wants to do the same thing with Pandas

import pandas as pd
import sqlite3
conn = sqlite3.connect("db.sqlite3")
table = pd.read_sql_query("SELECT name FROM sqlite_master WHERE type='table'", conn)
print(table)
Mukesh Yadav
  • 2,256
  • 2
  • 33
  • 51
19

Apparently the version of sqlite3 included in Python 2.6 has this ability: http://docs.python.org/dev/library/sqlite3.html

# Convert file existing_db.db to SQL dump file dump.sql
import sqlite3, os

con = sqlite3.connect('existing_db.db')
with open('dump.sql', 'w') as f:
    for line in con.iterdump():
        f.write('%s\n' % line)
checkit
  • 381
  • 1
  • 3
  • 8
  • 1
    Be careful with this, it will print all the data in your tables if they are populated with INSERT INTO statements! – RobinL Dec 22 '13 at 10:45
  • Thankfully, `INSERT INTO` statements are single line so easy to escape with `if line.startswith("INSERT INTO") ...` – ViFI Dec 29 '20 at 21:22
  • This works for me and answers the OP's question - how to get a dump file – user10186832 Aug 29 '23 at 10:21
8

Some might find my function useful if you just want to print out all of the tables and columns in your db.

In the loop, I query each TABLE with LIMIT 0 so it just returns the header info without all the data. You make an empty df out of it, and use the iterable df.columns to print each column name out.

conn = sqlite3.connect('example.db')
c = conn.cursor()

def table_info(c, conn):
    '''
    prints out all of the columns of every table in db
    c : cursor object
    conn : database connection object
    '''
    tables = c.execute("SELECT name FROM sqlite_master WHERE type='table';").fetchall()
    for table_name in tables:
        table_name = table_name[0] # tables is a list of single item tuples
        table = pd.read_sql_query("SELECT * from {} LIMIT 0".format(table_name), conn)
        print(table_name)
        for col in table.columns:
            print('\t' + col)
        print()

table_info(c, conn)
Results will be:

table1
    column1
    column2

table2
    column1
    column2
    column3 

etc.
ALee
  • 81
  • 1
  • 3
  • Since this post is for newer programmers you could include the import statements `import sqlite3` `import pandas as pd` – Tim Mar 09 '22 at 16:41
6

After a lot of fiddling I found a better answer at sqlite docs for listing the metadata for the table, even attached databases.

meta = cursor.execute("PRAGMA table_info('Job')")
for r in meta:
    print r

The key information is to prefix table_info, not my_table with the attachment handle name.

nealmcb
  • 12,479
  • 7
  • 66
  • 91
user3451435
  • 203
  • 2
  • 6
  • I got lots of errors in the snippet you wrote, and don't see e.g. "db_alias" in either the referenced docs or in other examples. In the context of the other examples, I think you want this line, for e.g. the `Job` table: `meta = cursor.execute("PRAGMA table_info('Job')")` And your first line seems unrelated to the rest. – nealmcb Jan 04 '15 at 18:41
2

Check out here for dump. It seems there is a dump function in the library sqlite3.

Angel
  • 818
  • 5
  • 7
  • I'm trying: import sqlite3 con = sqlite3.connect("test.db") con.dump() It fails... I keep checking – Angel Nov 20 '08 at 20:47
2
#!/usr/bin/env python
# -*- coding: utf-8 -*-

if __name__ == "__main__":

   import sqlite3

   dbname = './db/database.db'
   try:
      print "INITILIZATION..."
      con = sqlite3.connect(dbname)
      cursor = con.cursor()
      cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
      tables = cursor.fetchall()
      for tbl in tables:
         print "\n########  "+tbl[0]+"  ########"
         cursor.execute("SELECT * FROM "+tbl[0]+";")
         rows = cursor.fetchall()
         for row in rows:
            print row
      print(cursor.fetchall())
   except KeyboardInterrupt:
      print "\nClean Exit By user"
   finally:
      print "\nFinally"
VecH
  • 21
  • 1
0

I've implemented a sqlite table schema parser in PHP, you may check here: https://github.com/c9s/LazyRecord/blob/master/src/LazyRecord/TableParser/SqliteTableDefinitionParser.php

You can use this definition parser to parse the definitions like the code below:

$parser = new SqliteTableDefinitionParser;
$parser->parseColumnDefinitions('x INTEGER PRIMARY KEY, y DOUBLE, z DATETIME default \'2011-11-10\', name VARCHAR(100)');
c9s
  • 1,888
  • 19
  • 15