Python 3.x - SQLite 3 Database CRUD Operations Examples

We can make use of the sqlite3 module in Python to make use of the lightweight disk-based database SQLite that doesn’t require a separate server process.

One may use this database for devices that do not have support or enough storage for installing databases like Oracle, MySQL, or PostgreSQL, prototyping an application, or saving internal data.


This tutorial assumes that you already have experience working SQL with one of the RDBMS such as MySQL, Oracle, Microsoft SQL, or PostgreSQL.


Let's get started with how to create an SQLite database using sqlite3 module in Python.


Step 1: Creating an SQLite Database


Step 2: Create a cursor object to interact with our database


Step 3: Create a table


Step 4: Insert Operation Example


Step 5: Select and Print Results


Step 6: Update Example


Step 7: Delete Example


Complete Code:

import sqlite3

conn = sqlite3.connect('mydb.db')

cursor = conn.cursor()

# Create
cursor.execute('''
    CREATE TABLE IF NOT EXISTS employees (
        emp_id INTEGER PRIMARY KEY,
        emp_name TEXT,
        emp_dept TEXT)
''')

# Insert
cursor.execute("INSERT INTO employees (emp_name, emp_dept) VALUES (?, ?)", ('Sam', 'Finance'))
conn.commit()

cursor.execute("INSERT INTO employees (emp_name, emp_dept) VALUES (?, ?)", ('Mike', 'IT'))
conn.commit()

# Select 
cursor.execute("SELECT * FROM employees")
data = cursor.fetchall()

for row in data:
    print(row)

# Update
cursor.execute("UPDATE employees SET emp_dept = ? WHERE emp_name = ?", ('IT', 'Sam'))
conn.commit()

# Delete
cursor.execute("DELETE FROM employees WHERE emp_name = ?", ('Sam',))
conn.commit()
Python 3 + SQLite 3 Code Example

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!