SQLite with Python
SQLite in Python
SQLite is built into Python, in the sqlite3 module. There is nothing to install.
Tip: For a step by step introduction, see the Python SQLite chapter in our Python Tutorial.
Connect to a Database
sqlite3.connect() opens a database file, and creates it if it does not exist. A cursor runs the SQL statements:
import sqlite3
con = sqlite3.connect("northwind.db")
cur = con.cursor()
You can download the Northwind database in the SQLite Get Started chapter.
A Database in Memory
For testing, you can make a database in memory instead of in a file. Use the special name ":memory:". The database is new and empty every time the program runs, and it is gone when the program ends:
Example
Make a database in memory, add a table with three rows, and read them back:
import sqlite3
con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("""
CREATE TABLE Shippers (
ShipperID INTEGER PRIMARY KEY,
ShipperName TEXT,
Phone TEXT
)
""")
cur.execute("""
INSERT INTO Shippers VALUES
(1, 'Speedy Express', '(503) 555-9831'),
(2, 'United Package', '(503) 555-3199'),
(3, 'Federal Shipping', '(503) 555-9931')
""")
con.commit()
cur.execute("SELECT * FROM Shippers")
print(cur.fetchall())
Try it Yourself »
The other examples on this page also use a database in memory, so you can run them in our online editor. To keep the examples short, they show only the code that the section is about. Click "Try it Yourself" to see the complete code, which also creates the table and adds the rows.
Run a Query
execute() runs a statement, and fetchall() returns all the rows as a list of tuples:
Example
Select the customers from Germany:
cur.execute("""
SELECT CustomerName, City
FROM Customers
WHERE Country = 'Germany'
""")
for row in cur.fetchall():
print(row)
Try it Yourself »
fetchone() returns only the next row, or None if there are no more rows.
Use Parameters
When a value comes from a variable, write ? in the SQL, and give the values as a tuple. Never put the values into the SQL text yourself. Read why in the SQLite Injection chapter:
Example
Select the customers from the country in the variable country:
country = "UK"
cur.execute("""
SELECT * FROM Customers
WHERE Country = ?
""", (country,))
print(cur.fetchall())
Try it Yourself »
Note: A tuple with one value needs a comma: (country,).
Insert and Commit
After an INSERT, UPDATE or DELETE, call con.commit() to save the changes. cur.lastrowid is the id of the new row:
Example
Insert a shipper, and print its id:
name = "Fast Bikes"
phone = "(503) 555-1234"
sql = """
INSERT INTO Shippers (ShipperName, Phone)
VALUES (?, ?)
"""
cur.execute(sql, (name, phone))
con.commit()
print(cur.lastrowid)
Try it Yourself »
Warning: Without commit(), the changes are lost when the program ends.
Insert Many Rows
executemany() runs the statement once for each tuple in a list:
Example
Insert two shippers from a list:
shippers = [
("Fast Bikes", "(503) 555-1234"),
("Slow Boats", "(503) 555-9876"),
]
sql = """
INSERT INTO Shippers (ShipperName, Phone)
VALUES (?, ?)
"""
cur.executemany(sql, shippers)
con.commit()
Try it Yourself »
Get Rows as Dictionaries
Set row_factory to sqlite3.Row to get the values by column name:
Example
Print the name of each shipper:
con.row_factory = sqlite3.Row
cur = con.cursor()
cur.execute("SELECT * FROM Shippers")
for row in cur.fetchall():
print(row["ShipperName"])
Try it Yourself »
Handle Errors
When a statement breaks a rule, Python raises an exception, like sqlite3.IntegrityError. There is already a shipper with ShipperID 1:
Example
Catch the error when the ShipperID is already used:
try:
cur.execute(
"INSERT INTO Shippers (ShipperID)"
" VALUES (1)"
)
except sqlite3.IntegrityError as e:
print("Error:", e)
Try it Yourself »
Close the Connection
Close the connection when you are done:
con.close()
Learn more about Python in our Python Tutorial.