I\'m trying to find out a way to find the names of tables in a database(if any exist). I find that from a sqlite cli I can use:
>.tables
<
Here's a convenient printer I wrote based Martijn's response:
def printSchema(connection):
for (tableName,) in connection.execute(
"""
select NAME from SQLITE_MASTER where TYPE='table' order by NAME;
"""
):
print("{}:".format(tableName))
for (
columnID, columnName, columnType,
columnNotNull, columnDefault, columnPK,
) in connection.execute("pragma table_info('{}');".format(tableName)):
print(" {id}: {name}({type}){null}{default}{pk}".format(
id=columnID,
name=columnName,
type=columnType,
null=" not null" if columnNotNull else "",
default=" [{}]".format(columnDefault) if columnDefault else "",
pk=" *{}".format(columnPK) if columnPK else "",
))
result sets have a description that you can get some information from. It reveals some basic metadata like column name and number of columns.
>>> rs = c.execute('''SELECT * FROM news WHERE 1=0''');
>>> dir(rs)
['__class__', '__delattr__', '__doc__', '__format__',
'__getattribute__', '__hash__', '__init__', '__iter__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__',
'__str__', '__subclasshook__', 'arraysize', 'close', 'connection',
**'description'**, 'execute', 'executemany', 'executescript', 'fetchall',
'fetchmany', 'fetchone', 'lastrowid', 'next', 'row_factory',
'rowcount', 'setinputsizes', 'setoutputsize']
>>> print(rs.description)
(('id', None, None, None, None, None, None),
('imageUrl', None, None, None, None, None, None),
('headline', None, None, None, None, None, None),
('who', None, None, None, None, None, None))
Use sqlite row object. A row object has keys() that will give you the schema.
from docs.python.org
conn.row_factory = sqlite3.Row
c = conn.cursor()
c.execute('select * from stocks')
<sqlite3.Cursor object at 0x7f4e7dd8fa80>
r = c.fetchone()
type(r)
<type 'sqlite3.Row'>
r
(u'2006-01-05', u'BUY', u'RHAT', 100.0, 35.14)
r.keys()
['date', 'trans', 'symbol', 'qty', 'price']
You should be able access the table names from the sqlite_master
table.
SELECT name FROM sqlite_master WHERE type='table';
The names of the columns are not directly accessible. The easiest way to get them is to query the table and get the column names from the query result.
SELECT * FROM table_name LIMIT 1;
I just tried
SELECT name FROM my_db.sqlite_master WHERE type='table';
to combine Tom Kerr's answer and the attempt to retrieve information on an attached database. At first it didn't work. Turns out I first have to attach the other database this way:
ATTACH DATABASE 'file:my_other_database_file.db?cache=shared' as my_db;
otherwise the database will fail to obtain a read lock for the attached database's sqlite_master
(and all queries will succeed with zero results).
Just a hint in case anybody else stumbles upon that part of the issue.
To get the schema information, IMHO, below also works:
select sql from sqlite_master where type='table';