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.
Let's get started with how to create an SQLite database using sqlite3 module in Python.
Step 1: Creating an SQLite Database
import sqlite3
conn = sqlite3.connect('mydb.db')
We first import the sqlite3 module and then create the database connection using the connect() method from the sqlite3 module. If the database does not exist it will be created, else we connect it to the existing database.
Step 2: Create a cursor object to interact with our database
cursor = conn.cursor()
Next we need to create a cursor object that we will need to interact with our database and perform the CRUD - Create - Read - Update - Delete operations.
Step 3: Create a table
cursor.execute('''
CREATE TABLE IF NOT EXISTS employees (
emp_id INTEGER PRIMARY KEY,
emp_name TEXT,
emp_dept TEXT)
''')
Now we are good to create a SQLite Database table, the above example will create an employees table.
Below is the list of datatypes in SQLite.
SQLite Data Type | Description | Example |
---|---|---|
NULL | Represents a missing value. | NULL |
INTEGER | Whole numbers, signed/unsigned. | 101 |
REAL | Floating-point numbers. | 22.44 |
TEXT | Text strings. | 'Sammy' |
BLOB | Binary data. | [some binary data] |
NUMERIC | Any numeric value. | 1, 5, -11 |
Step 4: Insert Operation Example
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()
Step 5: Select and Print Results
cursor.execute("SELECT * FROM employees")
data = cursor.fetchall()
for row in data:
print(row)
Step 6: Update Example
cursor.execute("UPDATE employees SET emp_dept = ? WHERE emp_name = ?", ('IT', 'Sam'))
conn.commit()
Step 7: Delete Example
cursor.execute("DELETE FROM employees WHERE emp_name = ?", ('Sam',))
conn.commit()
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()
Facing issues? Have Questions? Post them here! I am happy to answer!
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
- How to convert int to ASCII in Python
- How to make use of SQLite Module in Python?
- Split a String into Sub-string and Parse in Python
- Python: Pandas Rename Columns with List Example
- How to run Python file from Mac Terminal
- How to Exit a Loop in Python Code
- Python: How to Plot a Histogram using Matplotlib and data as list
- MD5 Hashing in Python
- Jupyter: Safari Cant Connect to the Server localhost:8888/tree
- Fix: AttributeError: str object has no attribute decode. Did you mean: encode?[Python]
- How to Read a binary File with Python
- How to add two float numbers in Python
- Python: How to install YAML Package
- Python: How to Save Image from URL
- What is Markdown in Jupyter Notebook with Examples
- How to change the Python Default version
- 33: Python Program to send an email vid GMail
- How to comment code in Python
- How to Fix AttributeError in Python
- Fix: error: Jupyter command `jupyter-nbconvert` not found [VSCode]
- How to comment out a block of code in Python
- List of All 35 Reserved Keywords in Python Programming Language 3.11
- Import Other Python Files Examples
- Python: How to add Progress Bar in Console with Examples
- 3 Ways to convert bytes to String in Python
- Be right back Weβre making updates to the Apple Store. Check back soon. - Apple
- How to install XML Tools Plugin Notepad++ - NotepadPlusPlus
- Mac: How to quit Jupyter Notebook from Terminal - MacOS
- Save Java Object as JSON file using Jackson Library - Java
- SQLite with Android Easy to Understand Tutorial that covers Select, Insert, Update and Delete - Android
- Fix: rust-analyzer failed to discover workspace [Visual Studio Code] - Rust
- Float built-in function in Python - Python
- How to Make Google.com the Default Homepage on Safari on Mac - MacOS