Some Python Examples
← prev | next →     Top-level ToC     /sqlite.html     (printable version)
import sqlite3

# Connection object represents the database.
cnxn = sqlite3.connect('foo.db')

curs = cnxn.cursor()

curs.execute('create table ...')
curs.execute(...)
curs.executemany(...)

cnxn.commit() # Saves changes to db.

curs.execute('select ...')
a_row = curs.fetchone()
all_rows = curs.fetchall()

# Or, instead of fetchone() or fetchall(),
for row in curs.execute('select ...'):
    print(row)

curs.close()
cnxn.close()

If you want to skip cursors, you can just do cnxn.execute(...) or cnxn.executemany(...) and it will make an implicit temporary cursor to use.

Use the DB-API’s parameter substitution:

curs.execute('select ... where foo = ?', (some_val,))

That 2nd arg must be a tuple.

sqlite3 is developed externally under the name “pysqlite” at https://github.com/ghaering/pysqlite.