How to Use SQL Databases with Python: A Beginner-Friendly Tutorial

This tutorial will guide you through the process of using SQL databases with Python, focusing on MySQL as the database management system. You will learn how to set up your environment, connect to a database, and perform basic operations such as creating, reading, updating, and deleting records.
Prerequisites
Before you start, ensure you have the following installed:
- Python: Make sure Python is installed on your machine. You can download it from python.org.
- MySQL Server: You will need to have MySQL installed on your system to interact with it directly, run the commands, and set up the user permissions.Here’s how you can install MySQL on your system:
- Install MySQL (if not already installed):
- Secure the installation (sets up the root password and other settings):
- Access MySQL: Once MySQL is installed, you can log in to the MySQL shell:
- MySQL Connector for Python: Install the MySQL connector using pip. Open your command line and run:
Setting Up Your Python Environment
- Import Required Libraries Start by importing the necessary libraries in your Python script:
- Establish a Connection to the Database Use the following code to connect to your MySQL server:
Creating a Database
To create a new database, execute the following commands:
Creating Tables
Once the database is created, you need to create tables within it. Here’s how to create a simple teacher table:
Inserting Data into Tables
To insert data into your teacher table, use the following code:
Reading Data from Tables
To read data from the teacher table:
Updating Records
To update an existing record in the table:
Deleting Records
To delete a record from the table:
Closing the Connection
Finally, don’t forget to close your cursor and connection once you’re done:
Conclusion
This tutorial covers the basics of using SQL databases with Python. You learned how to set up your environment, create a database and tables, and perform basic CRUD (Create, Read, Update, Delete) operations. For more advanced topics like using SQL with Pandas or exploring different SQL databases like SQLite or PostgreSQL, consider checking out additional tutorials or courses. Feel free to experiment with more complex queries and database structures as you become more comfortable with SQL and Python!

Nikhil is an intern consultant at Marktechpost. He is pursuing an integrated dual degree in Materials at the Indian Institute of Technology, Kharagpur. Nikhil is an AI/ML enthusiast who is always researching applications in fields like biomaterials and biomedical science. With a strong background in Material Science, he is exploring new advancements and creating opportunities to contribute.