Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL SQLITE MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST DART PLAYWRIGHT TOOLS MATH SHEETS POWER BI

SQLite Tutorial

SQLite HOME SQLite Intro SQLite Get Started

SQLite SQL

SQLite SQL SQLite SELECT SQLite SELECT DISTINCT SQLite WHERE SQLite ORDER BY SQLite AND SQLite OR SQLite NOT SQLite INSERT INTO SQLite NULL Values SQLite UPDATE SQLite DELETE SQLite LIMIT SQLite Aggregate SQLite MIN() and MAX() SQLite COUNT() SQLite SUM() SQLite AVG() SQLite LIKE SQLite Wildcards SQLite GLOB SQLite IN SQLite BETWEEN SQLite Aliases SQLite Joins SQLite INNER JOIN SQLite LEFT JOIN SQLite RIGHT JOIN SQLite FULL JOIN SQLite CROSS JOIN SQLite Self Join SQLite UNION SQLite UNION ALL SQLite INTERSECT and EXCEPT SQLite GROUP BY SQLite HAVING SQLite EXISTS SQLite Subqueries SQLite INSERT INTO SELECT SQLite CASE SQLite NULL Functions SQLite Comments SQLite Operators

SQLite Advanced

SQLite UPSERT SQLite RETURNING SQLite WITH (CTE) SQLite Window Functions SQLite JSON

SQLite Database

SQLite Create DB SQLite Attach DB SQLite Create Table SQLite Drop Table SQLite Alter Table SQLite Data Types SQLite STRICT Tables SQLite Constraints SQLite NOT NULL SQLite UNIQUE SQLite PRIMARY KEY SQLite FOREIGN KEY SQLite CHECK SQLite DEFAULT SQLite AUTOINCREMENT SQLite Generated Columns SQLite Create Index SQLite Views SQLite Triggers SQLite Dates SQLite Transactions SQLite PRAGMA SQLite Injection

SQLite Tools

SQLite Command Line SQLite Import and Export SQLite with Python

SQLite References

SQLite Functions

SQLite Exercises

SQLite Editor SQLite Quiz SQLite Exercises

SQLite with Python


Share

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.




Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by W3Schools. All Rights Reserved. W3Schools is Powered by W3.CSS.