Back to Python
2026-05-135 min read

MySQL RDBMS (Python Programming)

Learn MySQL RDBMS (Python Programming) step by step with clear examples and exercises.

Title: MySQL RDBMS Python Programming - A full guide for Practical Depth

Why This Matters

In this lesson, we delve into the practical application of MySQL Relational Database Management System (RDBMS) using Python programming. Understanding MySQL and Python integration is crucial for real-world data management tasks, such as web development, data analysis, and system administration. Mastering these skills can help you solve common bugs encountered in projects and prepare for job interviews.

Prerequisites

To follow this tutorial, you should have a basic understanding of Python programming concepts, including variables, functions, loops, and data structures. Familiarity with SQL (Structured Query Language) is also beneficial but not mandatory as we will cover the essentials throughout this lesson. It's recommended to have a MySQL server installed locally or access to a remote MySQL server.

Setting Up Your Local MySQL Server (Optional)

If you don't have a MySQL server set up yet, follow these steps:

  1. Download and install MySQL Community Server on your local machine.
  2. Start the MySQL server by running mysqld in the command line.
  3. Create a new database and user with appropriate privileges:
CREATE DATABASE mydatabase;
CREATE USER 'myusername'@'localhost' IDENTIFIED BY 'mypassword';
GRANT ALL PRIVILEGES ON mydatabase.* TO 'myusername'@'localhost';
FLUSH PRIVILEGES;

Replace mydatabase, myusername, and mypassword with your desired database name, username, and password.

Core Concept

MySQL RDBMS allows for the management of structured data using a relational model. In Python, you can interact with MySQL databases using several libraries, such as mysql-connector-python. This library provides an interface to connect, query, and manipulate MySQL databases.

Connecting to a MySQL Database

To start working with MySQL in Python, first install the required package:

pip install mysql-connector-python

Next, create a Python script and import the necessary modules:

import mysql.connector

Now, you can establish a connection to your MySQL server using the following code:

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)

Replace host, user, password, and database with your MySQL server's details.

Creating a Table

To create a table in the connected database, use the cursor() function to access the cursor object, which will execute SQL queries:

mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE employees (id INT, firstname VARCHAR(255), lastname VARCHAR(255))")

Inserting Data

To insert data into the table, use the execute() function again with an SQL INSERT statement:

mycursor.execute("INSERT INTO employees (id, firstname, lastname) VALUES (1, 'John', 'Doe')")

Querying Data

To retrieve data from the table, use the execute() function with an SQL SELECT statement:

mycursor.execute("SELECT * FROM employees")

Iterate through the results using a for loop:

for x in mycursor:
print(x)

Closing the Connection

Finally, don't forget to close the connection when you're done:

mydb.close()

Worked Example

Let's create a complete Python script that connects to a MySQL server, creates a table called employees, inserts data for three employees, and queries the data using an SQL SELECT statement:

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)

mycursor = mydb.cursor()

mycursor.execute("CREATE TABLE employees (id INT, firstname VARCHAR(255), lastname VARCHAR(255))")

mycursor.execute("INSERT INTO employees (id, firstname, lastname) VALUES (1, 'John', 'Doe')")
mycursor.execute("INSERT INTO employees (id, firstname, lastname) VALUES (2, 'Jane', 'Smith')")
mycursor.execute("INSERT INTO employees (id, firstname, lastname) VALUES (3, 'Bob', 'Johnson')")

mycursor.execute("SELECT * FROM employees")

for x in mycursor:
print(x)

mydb.close()

Common Mistakes

  1. Not installing the mysql-connector-python package: Remember to run pip install mysql-connector-python.
  2. Incorrect connection details: Ensure you provide the correct host, username, password, and database for your MySQL server.
  3. Table creation syntax errors: Make sure your table creation SQL statement is valid and follows the correct syntax.
  4. Inserting data with incorrect data types: Be aware of the data types in your table and make sure you're inserting compatible values.
  5. Not closing the connection: Always close the database connection when you're done to free up resources.
  6. Forgetting to create a database or user before connecting: Make sure you have created a database and user with appropriate privileges before attempting to connect.

Practice Questions

  1. Write a Python script that connects to a MySQL server, creates a table called students, inserts data for three students, and queries the data using an SQL SELECT statement.
  2. Modify the example script to update the last name of the first student to 'Doe-Jones'.
  3. Write a Python script that connects to a MySQL server, creates a table called books, inserts data for five books, and queries the data using an SQL JOIN statement with another table named authors. The books table should have columns id, title, and author_id, while the authors table should have columns id and name.
  4. Write a Python script that creates a unique index on the id column of the employees table in your MySQL database.
  5. Write a Python script that retrieves all employees whose last name contains the string 'Doe'.

FAQ

Q: Can I use other libraries to interact with MySQL in Python?

A: Yes, there are several libraries available for interacting with MySQL databases in Python, such as pymysql and sqlalchemy.

Q: How do I handle errors when working with MySQL in Python?

A: You can use exception handling to catch errors that may occur while connecting to the database or executing SQL queries. For example:

try:

Your code here

except mysql.connector.Error as error:

print("Error:", error)


### Q: How do I create a unique index in MySQL using Python?
A: To create a unique index, use the `CREATE UNIQUE INDEX` SQL statement with your table and column names:

mycursor.execute("CREATE UNIQUE INDEX idx_employees_id ON employees (id)")


### Q: How do I create a foreign key constraint in MySQL using Python?
A: To create a foreign key constraint, use the `ALTER TABLE` SQL statement with your table and column names, as well as the referenced table and column names:

mycursor.execute("ALTER TABLE employees ADD FOREIGN KEY (author_id) REFERENCES authors(id)")

MySQL RDBMS (Python Programming) | Python | XQA Learn