How to make use of SQLite Module in Python?


If you want to make use of SQLite database with your Python program, then you can make use of the sqlite3 module.

Note that there is no sqlite module, if you try to import it you will get an error -

>>> import sqlite
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>

ModuleNotFoundError: No module named 'sqlite'

Example: SQLite + Python

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)

Note: SQLite is a part of the standard library of Python and you do not need to install sqlite3 using pip.

How to make use of SQLite with Python Example

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap