Skip to content

Sqlite

Python provides native support for SQLite database operations using the stdlib sqlite3 module.

Initializing a connection is as simple as:

import sqlite3

conn = sqlite3.connect("path/to/your/db.sqlite3")

To execute SQL statements, you also need to initialize a sqlite3.Cursor object:

c = conn.cursor()

Then you can execute statements against your database:

## Create a table
c.execute("CREATE TABLE movie(title, year, score)")

## Show table names
res = c.execute("SELECT name FROM sqlite_master")
res.fetchone()

## Insert data into the movie table
c.execute("""
    INSERT INTO movie VALUES
        ('Monty Python and the Holy Grail', 1975, 8.2),
        ('And Now for Something Completely Different', 1971, 7.5)
""")
Last updated on