sqlite3: SQLite in Python
Python Standard Library SQL interface
The Python Standard Library contains a module that provides an SQL interface with the DB-API 2.0 specification:
sqlite3
. It requires SQLite 3.7.15 or newer.
First, import the sqlite3
module:
import sqlite3
Then, connect to the SQLite database file and create a cursor:
db = "example.db"
con = sqlite3.connect(db)
cur = con.cursor()
To get the list of all the tables in the database:
tables = cur.execute("SELECT name FROM sqlite_schema WHERE type='table'").fetchall()
To get a single table name:
tables = cur.execute("SELECT name FROM sqlite_schema WHERE type='table'").fetchall()
if len(tables) != 1: # length can be 0 (no table) or >1 (more than one table)
if len(tables) == 0:
raise ValueError(f"The database {db} contains no table.")
else:
raise ValueError(f"The database {db} contains more than one table: {[table[0] for table in tables]}.")
table_name = tables[0][0]
If we are sure there is only a single table:
table_name = cur.execute("SELECT name FROM sqlite_schema WHERE type='table'").fetchone()[0]
To iterate over the rows of the table table_name
:
cur.row_factory = sqlite3.Row
for row in cur.execute(f"SELECT * FROM {table_name}"):
print(dict(row))
{'date': '2006-01-05', 'trans': 'BUY', 'symbol': 'RHAT', 'qty': 100.0, 'price': 35.14}
{'date': '2006-03-28', 'trans': 'BUY', 'symbol': 'IBM', 'qty': 1000.0, 'price': 45.0}
{'date': '2006-04-06', 'trans': 'SELL', 'symbol': 'IBM', 'qty': 500.0, 'price': 53.0}
{'date': '2006-04-05', 'trans': 'BUY', 'symbol': 'MSFT', 'qty': 1000.0, 'price': 72.0}
At the end, close the connection:
con.close()