Python with MySQL CRUD Operations: A Practical Guide

Estimated read time 2 min read

Introduction

Performing CRUD operations (Create, Read, Update, Delete) in a MySQL database using Python is a fundamental skill for many applications. In this guide, we’ll walk through each CRUD operation step by step, using the mysql-connector-python library for database interactions.

1. Setting Up MySQL Database:

  • Start by setting up a MySQL database and creating a table for our CRUD operations. For this example, let’s create a simple users table.
   CREATE TABLE users (
       id INT AUTO_INCREMENT PRIMARY KEY,
       username VARCHAR(255),
       email VARCHAR(255)
   );

2. Installing the MySQL Connector:

  • Install the mysql-connector-python library using pip.
   pip install mysql-connector-python

3. Connecting to the MySQL Database:

  • Use the following Python script to connect to your MySQL database.
   import mysql.connector

   # Replace 'your_database', 'your_username', and 'your_password' with your actual database credentials
   db = mysql.connector.connect(
       host='localhost',
       user='your_username',
       password='your_password',
       database='your_database'
   )

   cursor = db.cursor()

4. Create Operation:

  • Let’s write a function to add a new user to the users table.
   def create_user(username, email):
       query = "INSERT INTO users (username, email) VALUES (%s, %s)"
       values = (username, email)

       cursor.execute(query, values)
       db.commit()

5. Read Operation:

  • Retrieve users from the users table.
   def read_users():
       query = "SELECT * FROM users"

       cursor.execute(query)
       result = cursor.fetchall()

       for user in result:
           print(user)

6. Update Operation:

  • Update the email of a specific user.
   def update_user_email(user_id, new_email):
       query = "UPDATE users SET email = %s WHERE id = %s"
       values = (new_email, user_id)

       cursor.execute(query, values)
       db.commit()

7. Delete Operation:

  • Delete a user from the users table.
   def delete_user(user_id):
       query = "DELETE FROM users WHERE id = %s"
       values = (user_id,)

       cursor.execute(query, values)
       db.commit()

8. Using the CRUD Operations:

  • Now, let’s use these functions to perform CRUD operations.
   # Create a new user
   create_user('john_doe', '[email protected]')

   # Read all users
   read_users()

   # Update the email of user with ID 1
   update_user_email(1, '[email protected]')

   # Read all users after the update
   read_users()

   # Delete user with ID 2
   delete_user(2)

   # Read all users after the deletion
   read_users()

9. Closing the Database Connection:

  • After performing CRUD operations, it’s essential to close the database connection.
   cursor.close()
   db.close()

Conclusion:

  • This guide provides a foundation for implementing CRUD operations in MySQL using Python. Customize the functions as needed for your specific use case. Additionally, consider using an ORM (Object-Relational Mapping) library like SQLAlchemy for more complex applications.

Related Articles