Performing CRUD Operations in Python: Step-by-Step Guide
Python MySQL database connection example
CRUD stands for Create, Read, Update, and Delete — the four basic operations used when working with databases. In Python, performing CRUD operations is simple thanks to its built-in libraries and connectors for databases like SQLite, MySQL, and PostgreSQL.
In this article, we’ll walk through the steps required to perform CRUD operations in Python, with examples using SQLite and MySQL.
Create – Insert new data into a database.
Read – Retrieve existing data.
Update – Modify existing records.
Delete – Remove unwanted data.
These operations are the foundation of all data-driven applications.
For SQLite (comes pre-installed):
# No installation required
For MySQL:
pip install mysql-connector-python
import sqlite3
connection = sqlite3.connect("mydatabase.db")
cursor = connection.cursor()
import mysql.connector
connection = mysql.connector.connect(
host="localhost",
user="root",
password="yourpassword",
database="testdb"
)
cursor = connection.cursor()
cursor.execute("""CREATE TABLE IF NOT EXISTS employees (
id INTEGER PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50),
salary FLOAT)""")
cursor.execute("INSERT INTO employees (name, salary) VALUES (%s, %s)", ("Alice", 60000))
connection.commit()
cursor.execute("SELECT * FROM employees")
for row in cursor.fetchall():
print(row)
cursor.execute("UPDATE employees SET salary = %s WHERE name = %s", (70000, "Alice"))
connection.commit()
cursor.execute("DELETE FROM employees WHERE name = %s", ("Alice",))
connection.commit()
connection.close()
Always close the connection to free up resources.
Use parameterized queries to prevent SQL injection.
Handle exceptions with try-except
blocks.
Always close database connections after use.
Use connection pooling for performance in large-scale applications.
Leverage ORMs like SQLAlchemy for complex projects.
User management systems – Adding, updating, and removing users.
E-commerce websites – Managing products, orders, and customers.
Banking applications – Handling accounts and transactions.
Machine learning projects – Storing datasets and predictions.
CRUD operations are the building blocks of any database-driven Python application. By following the steps outlined above, you can easily perform create, read, update, and delete operations in both SQLite and MySQL. Mastering CRUD operations is essential for backend development, data science, and enterprise-level applications.