sqlite3

What it is good for?

Create and use a SQLite database.

SQLite databases are stored in files. For using the sqlite3 module you don’t need to install or set up anything. SQLite is sufficient only for small SQL databases, but Python modules for bigger databases look very similar.

Installed with Python by default?

yes

Example

Create a new database:

  1. import sqlite3
  2. DB_SETUP = '''
  3. CREATE TABLE IF NOT EXISTS person (
  4. id INTEGER,
  5. name VARCHAR(32),
  6. description TEXT
  7. );'''
  8. db = sqlite3.connect('hamlet.db')
  9. db.executescript(DB_SETUP)

Insert data:

  1. query = 'INSERT INTO person VALUES (?,?,?)'
  2. db.execute(query, (1, "Hamlet", "the prince of Denkmark"))
  3. db.execute(query, (2, "Polonius", "Ophelias father"))
  4. db.commit()

Submit a query:

  1. query = '''SELECT name, description FROM person'''
  2. result = db.execute(query)
  3. print(list(result))
  4. db.close()

Where to learn more?

docs.python.org/3.5/library/sqlite3.html