How to work with database files with Python and SQLite


Creating a Database

SQLite works with database files. If you don't have a database file, already you can create one from scratch.

To create a new SQLite database, you connect to it. If the database file doesn't exist, SQLite will create it for you.

import sqlite3
# Connect to SQLite database (or create it if it doesn't exist)
conn = sqlite3.connect('school.db') # Create a cursor object
cursor = conn.cursor() # Close the connection
conn.close()

Creating a Table

You can create a table using the SQL CREATE TABLE statement.

import sqlite3
# Connect to SQLite database
conn = sqlite3.connect('school.db')
cursor = conn.cursor() # Create a table
cursor.execute('''
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY,
name TEXT,
age INTEGER,
grade TEXT
)
''') # Commit changes and close the connection
conn.commit()
conn.close()

Inserting Data

You can insert data into the table using the INSERT INTO statement.

import sqlite3
# Connect to SQLite database
conn = sqlite3.connect('school.db')
cursor = conn.cursor() # Insert data
cursor.execute('''
INSERT INTO students (name, age, grade)
VALUES ('Alice', 14, '8th')
''') cursor.execute('''
INSERT INTO students (name, age, grade)
VALUES ('Bob', 15, '9th')
''') # Commit changes and close the connection
conn.commit()
conn.close()

Querying Data

You can query data using the SELECT statement.

import sqlite3
# Connect to SQLite database
conn = sqlite3.connect('school.db')
cursor = conn.cursor() # Query data
cursor.execute('''
SELECT * FROM students WHERE age >= 14
''') # Fetch and print all rows
rows = cursor.fetchall()
for row in rows:
print(row) # Close the connection
conn.close()

Updating Data

You can update data using the UPDATE statement.

import sqlite3
# Connect to SQLite database
conn = sqlite3.connect('school.db')
cursor = conn.cursor() # Update data
cursor.execute('''
UPDATE students
SET grade = '10th'
WHERE name = 'Bob'
''') # Commit changes and close the connection
conn.commit()
conn.close()

Deleting Data

You can delete data using the DELETE FROM statement.

import sqlite3
# Connect to SQLite database
conn = sqlite3.connect('school.db')
cursor = conn.cursor() # Delete data
cursor.execute('''
DELETE FROM students WHERE name = 'Alice'
''') # Commit changes and close the connection
conn.commit()
conn.close()

Recommended Course

Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.