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: Rakesh
Author Info:

Rakesh is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

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