Skip to main content

Command Palette

Search for a command to run...

CRUD Operations in Python on MySQL

Updated
CRUD Operations in Python on MySQL
Y

Tech Lead & Architect | 13+ Years in Cloud, Backend, and AI - Experienced software engineer with expertise in Java, Spring Boot, Microservices, Angular, React, Kafka, DevOps, Python, PySpark, Databricks, and Generative AI. Certified in TOGAF, AWS, and Google Cloud. Passionate about building scalable, secure, and high-performance systems. Enthusiast in Data Engineering & Agentic AI. Author of 1,200+ technical articles sharing insights across diverse tech stacks.

Date: 2021-03-16

This article explores how to perform Create, Read, Update, and Delete (CRUD) operations on a MySQL database using Python. CRUD operations are fundamental to interacting with databases; they represent the core functions of creating new data, retrieving existing data, modifying data, and removing data. This tutorial focuses on achieving these actions using Python and the MySQL Connector/Python library, which acts as a bridge between the Python programming language and the MySQL database system.

Before diving into the process, it’s crucial to ensure that you have both Python and the MySQL Connector/Python installed on your system. Python can be downloaded from the official Python website, with installation instructions provided for various operating systems. Once Python is installed, the MySQL Connector/Python library can be installed using pip, the package installer for Python. This installation involves opening a command prompt or terminal and typing a simple command, which downloads and installs the necessary files. This installation command makes the library’s capabilities accessible within your Python scripts.

To simplify the process of setting up and interacting with a MySQL server, the tutorial recommends using Docker. Docker is a containerization technology that makes it easier to create and manage isolated software environments. A specific command is given to launch a Docker container which automatically sets up a MySQL server including a pre-created database named 'employee'. This removes the need for manual installation and configuration of the MySQL server, thereby streamlining the tutorial. After the successful setup, confirming the server's running status involves a simple command to check for running containers.

A conceptual diagram is implicitly mentioned, illustrating the relationship between the Python application, the MySQL Connector/Python library, and the MySQL server. This diagram is helpful in understanding how data flows between the components. The Python application sends requests to the MySQL server through the Connector/Python library, which translates these requests into a format understood by the server. The server then processes these requests and sends the results back to the Python application, again via the Connector/Python library.

The next phase involves setting up configuration files. A configuration file, named local.env, stores the connection details needed to access the MySQL database. These details include the hostname or IP address of the database server, the username, password, and the name of the database itself. Keeping these details in a separate file is a best practice for security reasons, preventing hardcoding sensitive information directly into the Python code.

Another Python script, described as readdbconfig.py, reads the settings from the local.env file. This script utilizes the configparser module, a built-in Python library for parsing configuration files. The script then creates an object representing the database connection details, making this information easily accessible to the other parts of the application.

Then, a script, connecttomysqldb.py, demonstrates the process of establishing a connection to the MySQL server. This script uses the previously loaded configuration details and the MySQL Connector/Python library to create a connection object. This object acts as the gateway to performing all subsequent database interactions.

Once connected, a script named createtable.py creates the necessary database table. This script includes instructions to check if the table already exists; it will either create the table or handle potential errors should the table already be present.

Subsequently, data is inserted into the table using a script referred to as insertdata.py. The script carefully checks for the presence of existing data to avoid duplicate entries. If data already exists, the insert operation is skipped; otherwise, default employee data is added.

Reading data from the table is illustrated by the getall.py script. This script retrieves all entries from the employee table and displays them on the console. It includes handling for the scenario where the table is empty.

Updating existing data is shown in a script, update.py. This script finds a specific record in the database based on an employee ID and modifies specified fields within that record. It includes error handling for situations where the specified employee ID is not found.

Finally, deleting records is covered in the delete.py script. This script removes a record based on a given employee ID, also including error handling for cases where the ID doesn't exist.

The tutorial concludes by mentioning the potential creation of additional scripts, such as one for deleting all records in the database. The article emphasizes that this comprehensive explanation covers the core CRUD operations in Python with MySQL, equipping readers with the foundational knowledge for managing database interactions within their applications. The entire process highlights the importance of modularity and error handling in database interaction scripts. Using separate files for configuration, connection, and each CRUD operation promotes code clarity and maintainability. Proper error handling prevents unexpected application crashes and ensures robust database management. These fundamental practices are key for building reliable and scalable database-driven applications.

Read more

More from this blog

The Engineering Orbit

1174 posts

The Engineering Orbit shares expert insights, tutorials, and articles on the latest in engineering and tech to empower professionals and enthusiasts in their journey towards innovation.