Master Python 3 MySQL: The Ultimate Guide to Database Integration

Python, a powerful and versatile programming language, is widely used for various applications, including data analysis, machine learning, and web development. When it comes to working with databases, Python offers numerous libraries and frameworks that simplify the process. One such library is mysql-connector-python, which facilitates interactions with MySQL databases from Python scripts.

Python MySQL Select
Python MySQL Select

The latest version of Python, Python 3, is a significant improvement over its predecessors. It comes with several enhancements that make it a preferred choice for many developers. In this article, we will explore how to use Python 3 to connect with and manipulate MySQL databases.

All Important Python Functions for Beginners (Complete Cheat Sheet)
All Important Python Functions for Beginners (Complete Cheat Sheet)

Installation and Setup

Before we dive into using Python 3 with MySQL, we need to ensure we have the necessary libraries installed. The main library we'll use is mysql-connector-python, provided by Oracle.

an image of a black background with the words credit card variation in python
an image of a black background with the words credit card variation in python

To install it, you can use pip, Python's package manager. Open your terminal or command prompt and run the following command:

pip install mysql-connector-python
a diagram showing the different types of python's programming skills and their uses in web design
a diagram showing the different types of python's programming skills and their uses in web design

Verifying the Installation

Once the installation is complete, you can verify it by importing the library in a Python script. Create a new Python file and add the following code:

import mysql.connector
print(mysql.connector.__version__)
Python Cheat Sheet for Beginners 2026 | Python Basics, Syntax, Loops, Functions & Variables
Python Cheat Sheet for Beginners 2026 | Python Basics, Syntax, Loops, Functions & Variables

When you run this script, it should print the version of the mysql-connector-python library, confirming that it's installed correctly.

Connecting to a MySQL Database

Now that we've installed the necessary library, we can connect to a MySQL database using Python. Here's a simple script that establishes a connection to a MySQL server:

three different types of python programming
three different types of python programming
import mysql.connector

db_config = {
    "host": "localhost",
    "user": "your_username",
    "password": "your_password",
    "database": "your_database"
}

connection = mysql.connector.connect(**db_config)

cursor = connection.cursor()
print("Connected to the database")

Replace the placeholders with your actual MySQL credentials and database name.

an image of a computer screen with the text'generation ascii art in python '
an image of a computer screen with the text'generation ascii art in python '
Python Cheat Sheet for Beginners
Python Cheat Sheet for Beginners
wallpaper_python
wallpaper_python
python programming
python programming
an image of a computer screen with cats on it and the words, python list method
an image of a computer screen with cats on it and the words, python list method
SQL Course for Beginners [Full Course]
SQL Course for Beginners [Full Course]
30-Day Python Learning Plan for Beginners | Complete Python Roadmap to Learn Coding Fast
30-Day Python Learning Plan for Beginners | Complete Python Roadmap to Learn Coding Fast
Python Unit 3 Cheat Sheet 🐍 | Functions, Arguments, Lambda & Modules (AKTU)
Python Unit 3 Cheat Sheet 🐍 | Functions, Arguments, Lambda & Modules (AKTU)
Python Learning Path for Beginners 2026 πŸš€
Python Learning Path for Beginners 2026 πŸš€
AI and Machine Learning Projects in Python – Fast & Efficient
AI and Machine Learning Projects in Python – Fast & Efficient
Python Complete Roadmap πŸπŸ’»
Python Complete Roadmap πŸπŸ’»
Python List Methods
Python List Methods
an image of a computer screen with many lines and numbers on the bottom half of it
an image of a computer screen with many lines and numbers on the bottom half of it
a poster with different types of logos and symbols on it, including the words'python library
a poster with different types of logos and symbols on it, including the words'python library
Clean Python: Elegant Coding in Python
Clean Python: Elegant Coding in Python
Python Data Structures Cheat Sheet for Beginners (Lists, Tuples, Sets & Dictionaries)
Python Data Structures Cheat Sheet for Beginners (Lists, Tuples, Sets & Dictionaries)
Python For Everything – Top Libraries & What They’re Used For
Python For Everything – Top Libraries & What They’re Used For
a computer screen showing the different types of commands and symbols for each type of device
a computer screen showing the different types of commands and symbols for each type of device
python
python

Executing SQL Queries

With a successful connection, you can now interact with your database using SQL queries. Python provides a simple and intuitive API for executing these queries.

Using the cursor object

The cursor object in the mysql-connector-python library is used to execute SQL commands. Here's how you can use it to fetch data from a table:

query = "SELECT * FROM employees"
cursor.execute(query)

results = cursor.fetchall()

for row in results:
    print(row)

Take note of the fetchall method, which retrieves all the rows of a query result. You can also use fetchone to get the first row and fetchmany(size) to get a specified number of rows.

Using prepared statements

When dealing with user input or parameters in your queries, it's essential to use prepared statements to prevent SQL injection attacks. Here's an example of using prepared statements with the cursor object:

emp_id = input("Enter employee ID: ")
query = "SELECT * FROM employees WHERE id = %s"

cursor.execute(query, (emp_id,))

result = cursor.fetchone()

if result:
    print(result)
else:
    print("No employee found with the given ID.")

In this example, the %s placeholder is replaced with the actual value of the emp_id variable when the query is executed.

Performing Database Operations

Python 3, in conjunction with the mysql-connector-python library, allows you to perform various database operations, such as creating tables, inserting data, updating records, and deleting data.

Creating a table

To create a table in your MySQL database using Python, you can use the following script:

query = '''
CREATE TABLE customers (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255),
    email VARCHAR(255)
)
'''

cursor.execute(query)

print("Table created successfully")

Inserting data into a table

Inserting data into a table is equally simple. Below is a script that inserts records into the customers table:

query = "INSERT INTO customers (name, email) VALUES (%s, %s)"
values = [
    ("John Doe", "johndoe@example.com"),
    ("Jane Smith", "janesmith@example.com")
]

cursor.executemany(query, values)

connection.commit()

print(cursor.rowcount, "records inserted successfully.")

The executemany method is used to insert multiple records at once.

Handling Errors and Exceptions

In any database-related operation, it's crucial to handle potential errors and exceptions to maintain the integrity and security of your data. Below is an example of how to use try/except blocks to handle exceptions when executing SQL queries:

try:
    cursor.execute(query)
    connection.commit()
    print("Query executed successfully")
except mysql.connector.Error as err:
    print(f"An error occurred: {err.errno} - {err.message}")
    connection.rollback()

In this example, any error that occurs during the execution of a query will be caught and handled, preventing the changes from being committed to the database.

As you've seen, Python 3, together with the mysql-connector-python library, offers a powerful and efficient way to work with MySQL databases. By following the best practices highlighted in this article, you canwrite robust and secure scripts to manipulate your MySQL data with ease. Happy coding!

Related Articles

Python Turtle Graphics Commands Python Numpy Tutorial W3schools Length Of List Python W3schools Python3 Mysql Python Numpy Library In Python W3schools Python Turtle Graphics Functions Python Using Ai W3schools What Is The Best Gui For Python 2d List Python W3schools Python Map W3