MyInternships.in

Python for Data & Web

Python SQLite Database

SQLite is a lightweight, file-based database, and Python's built-in sqlite3 module lets you create and query one without installing anything extra or running a separate database server.


Connecting to a Database

sqlite3 is part of the Python standard library, so no pip install is needed. connect() opens (or creates, if it doesn't exist yet) a database file, and cursor() gives you an object used to run SQL commands against it.

Connecting and creating a cursor
Python
import sqlite3

conn = sqlite3.connect("students.db")
cursor = conn.cursor()

Creating a Table

Use execute() with a CREATE TABLE statement to define the table's columns and data types, just like in plain SQL.

Creating a table
Python
cursor.execute("""
    CREATE TABLE IF NOT EXISTS students (
        id INTEGER PRIMARY KEY,
        name TEXT,
        age INTEGER
    )
""")

Inserting and Querying Data

INSERT adds new rows, and SELECT retrieves them. After a SELECT, use fetchall() (or fetchone()) on the cursor to pull the matching rows back into Python.

Inserting and selecting rows
Python
cursor.execute("INSERT INTO students (name, age) VALUES ('Aarav', 21)")
conn.commit()

cursor.execute("SELECT * FROM students")
rows = cursor.fetchall()
for row in rows:
    print(row)
⚠️

Always call conn.commit() after INSERT, UPDATE, or DELETE statements, or your changes will not be saved to the database file.

Parametrised Queries

Never build SQL strings by inserting variables directly with an f-string or plus signs — it opens the door to SQL injection. Instead, use a ? placeholder in the query and pass the values as a separate tuple; sqlite3 handles the safe substitution for you.

Safe parametrised queries
Python
name = "Diya"
age = 24
cursor.execute(
    "INSERT INTO students (name, age) VALUES (?, ?)",
    (name, age)
)
conn.commit()

cursor.execute("SELECT * FROM students WHERE age > ?", (20,))
adults = cursor.fetchall()
print(adults)

Closing the Connection

Once you're done, close the connection to free up the file. Wrapping database code in a try/except/finally block, or using the connection as a context manager, helps make sure it always closes cleanly, even if an exception occurs.

Closing the connection
Python
conn.close()
StepMethod
Connectsqlite3.connect("file.db")
Run SQLcursor.execute(sql, params)
Save changesconn.commit()
Read resultscursor.fetchall() / fetchone()
Finishconn.close()

Related Python Topics

Keep learning with these closely related lessons.

Ready to use your Python skills?

Find Python, data science and software internships and fresher jobs across India.

Browse Python Internships