sqlite3 — DB-API 2.0 interface for SQLite databases

Python comes with an API for working with a SQLite database.

Here is the basic setup:

import sqlite3

# create connection to database
con = sqlite3.connect("some_database.db")

# create cursor object
cur = con.cursor()

The connection object created by calling sqlite3.connect() is required to establish a connection to the database. If the database with the supplied name does not exists, it will create a new database in the current working directory.

The connection object contains a .cursor() method to create a cursor instance. A cursor is a object that allows us to perform some unit of work or transaction on our database.

  1. Connect to the database.
  2. Create a cursor to execute a transaction on the database.

Execute

cur.execute("CREATE TABLE movie(title, year, score)")
cur.execute("""INSERT INTO movie VALUES
        ('Monty Python and the Holy Grail', 1975, 8.2),
        ('And Now for Something Completely Different', 1971, 7.5)""")

SQL Parameters with Python Variables

To avoid SQL injection,