1. Introduction to MySQL Connector/Python
MySQL Connector/Python is the official library that allows Python programs to connect to a MySQL database and perform database operations. It enables you to handle essential tasks such as connecting to the database, executing queries, and retrieving or updating data in a simple and efficient way. A key advantage of MySQL Connector/Python is its direct integration with MySQL and its compliance with DB-API 2.0, which is the standard Python database API specification. This provides a consistent interface similar to accessing other database systems, allowing Python developers to work with databases in a uniform manner.
Why Use MySQL Connector/Python?
By using MySQL Connector/Python, you can perform secure database operations that help prevent SQL injection. It also allows you to take advantage of Python’s object-oriented programming features to implement database operations more efficiently and flexibly. In addition, it provides advanced features such as prepared statements and escaping, making it an excellent choice in terms of both performance and security.
2. Setting Up MySQL Connector/Python
To start using MySQL Connector/Python, you first need to prepare your environment. Below, we explain the installation steps and environment setup.
How to Install
MySQL Connector/Python can be easily installed using pip, Python’s package management tool. Run the following command to install it.
pip install mysql-connector-pythonAfter running this command, the latest version of MySQL Connector/Python will be installed.
Configuring Your Development Environment
To develop efficiently with MySQL Connector/Python, using an integrated development environment (IDE) can be very helpful. For example, IDEs such as PyCharm and VS Code provide features like code completion and debugging, which can improve productivity. In your IDE settings, select the appropriate Python interpreter and make sure it is configured to use the installed MySQL Connector/Python package.
3. Connecting to MySQL
Next, let’s go through the steps to connect to a MySQL database using MySQL Connector/Python. First, we’ll cover the basic concept of a connection and how to set the required parameters.
Setting Connection Parameters
To connect to a MySQL database, you need the following information.
host: The hostname or IP address of the database serveruser: The database usernamepassword: The user passworddatabase: The name of the database to connect to
Using this information, you can call the connect function of MySQL Connector/Python to connect to the database.
Sample Code
Below is a basic code example for connecting to a MySQL database.
import mysql.connector
# Connect to the database
conn = mysql.connector.connect(
host='localhost',
user='your_username',
password='your_password',
database='your_database'
)
# Check whether the connection was successful
if conn.is_connected():
print('Connected to the MySQL database.')
# Close the connection
conn.close()In this code, the connection is established to MySQL using the specified host, username, password, and database name. You can verify whether the connection succeeded by using the is_connected() method. When you no longer need the connection, make sure to close it using the close() method.

4. Database Operation Basics
Once you can connect to the database using MySQL Connector/Python, the next step is to perform basic database operations. In this section, we explain how to create tables and how to insert, retrieve, update, and delete data.
4.1 Creating a Table
First, let’s see how to create a new table in the database. The following code is an example of creating a table named users.
# Get a cursor
cursor = conn.cursor()
# Query to create a table
create_table_query = '''
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL
)
'''
# Create the table
cursor.execute(create_table_query)This code creates the users table only if it does not already exist. The id column is the primary key and is set to auto-increment.
4.2 Inserting Data
Next, let’s insert data into the table.
# Query to insert data
insert_data_query = '''
INSERT INTO users (username, email) VALUES (%s, %s)
'''
# Data to insert
user_data = ("Tanaka", "tanaka@example.com")
# Insert the data
cursor.execute(insert_data_query, user_data)
# Commit the changes
conn.commit()This code inserts a new user’s data into the users table. The %s values are placeholders that will be replaced with the data you provide.
4.3 Retrieving Data
Let’s also look at how to retrieve data from the table.
# Query to retrieve data
select_query = "SELECT * FROM users WHERE username = %s"
# Retrieve the data
cursor.execute(select_query, ("Tanaka",))
# Fetch the result
result = cursor.fetchone()
print(result)This code retrieves the record from the users table where the username is Tanaka.
4.4 Updating Data
Here is how to update existing data.
# Query to update data
update_query = "UPDATE users SET email = %s WHERE username = %s"
# Update the data
cursor.execute(update_query, ("tanaka.new@example.com", "Tanaka"))
# Commit the changes
conn.commit()This code updates Tanaka’s email address to a new one.
4.5 Deleting Data
Finally, here is how to delete data.
# Query to delete data
delete_query = "DELETE FROM users WHERE username = %s"
# Delete the data
cursor.execute(delete_query, ("Tanaka",))
# Commit the changes
conn.commit()This code deletes the record from the users table where the username is Tanaka.
5. Placeholders and Prepared Statements
In MySQL Connector/Python, you can improve security and performance by using placeholders and prepared statements when executing SQL queries. By leveraging these features, you can reduce security risks such as SQL injection and improve query execution efficiency.
5.1 Using Placeholders
By using placeholders, you can dynamically specify values inside an SQL query. This is also an effective way to prevent SQL injection. Below is an example of an SQL query using placeholders.
# Query to retrieve data
select_query = "SELECT * FROM users WHERE username = %s"
# Execute the query using a placeholder
cursor.execute(select_query, ("Tanaka",))
# Fetch the result
result = cursor.fetchone()
print(result)Here, %s is the placeholder, and it will be replaced with the value provided as the second argument to the execute method. With this approach, the input value is automatically escaped, helping to prevent SQL injection.
5.2 Using Prepared Statements
A prepared statement is a technique that improves performance when executing the same query multiple times. The SQL statement is parsed once at the beginning, and subsequent executions can skip parsing, making the process faster. Below is an example of how to use prepared statements in MySQL Connector/Python.
# Create a cursor (prepared statement enabled)
cursor = conn.cursor(prepared=True)
# Prepared statement query
stmt = "SELECT * FROM users WHERE username = ?"
# Execute the query
cursor.execute(stmt, ("Tanaka",))
# Fetch the result
result = cursor.fetchone()
print(result)By specifying prepared=True when creating the cursor, prepared statements are enabled. Also, note that prepared statements use ? instead of %s as the placeholder.
Benefits of Prepared Statements
- Security: Prevents SQL injection, just like placeholders.
- Performance: Improves efficiency when executing the same query repeatedly because parsing is performed only once.

6. Escaping and Executing SQL from a Connection
Escaping is required when dynamically generating SQL queries or handling data that contains special characters. MySQL Connector/Python provides convenient functions to handle escaping.
6.1 Escaping
With MySQL Connector/Python, you don’t have to implement escaping manually. You can use the converter.escape function of the connection object to escape values easily. The example below shows how to safely handle data that includes a single quote.
# Example of escaping
escaped_string = conn.converter.escape("O'Reilly")
print(escaped_string) # Output: O'ReillyBy escaping values in this way, you can safely generate SQL queries even when special characters are included.
6.2 Executing SQL Directly from the Connection
Normally, you execute SQL queries using a cursor. However, in some cases, you can execute SQL directly using the cmd_query method of the connection object. That said, this method does not support placeholders, and you must handle escaping yourself, so it should be used with caution.
# Execute an SQL query directly
stmt = "SELECT * FROM users WHERE username = '%s'"
conn.cmd_query(stmt % conn.converter.escape("Tanaka"))With this approach, you must place quotes correctly around %s and apply escaping properly. For most use cases, it is recommended to use a cursor along with placeholders instead.
7. Error Handling and Database Best Practices
Errors can occur during database operations, so proper error handling is essential. You should also understand best practices for operating a database safely and efficiently.
7.1 Implementing Error Handling
When using MySQL Connector/Python, it is recommended to use a try-except block to catch errors and handle them appropriately. Below is an example of implementing error handling.
import mysql.connector
from mysql.connector import Error
try:
conn = mysql.connector.connect(
host='localhost',
user='your_username',
password='your_password',
database='your_database'
)
cursor = conn.cursor()
cursor.execute("SELECT * FROM users")
results = cursor.fetchall()
for row in results:
print(row)
except Error as e:
print(f"An error occurred: {e}")
finally:
if conn.is_connected():
cursor.close()
conn.close()
print("The MySQL connection has been closed.")Inside the try block, database operations are performed. In the except block, errors are caught and an appropriate message is displayed. Finally, the finally block ensures the connection is closed. This allows the program to safely terminate the connection even if an error occurs.
7.2 Database Best Practices
- Manage connections: Database connections consume resources, so always close them when they are no longer needed.
- Use placeholders: To prevent SQL injection, always use placeholders for values in SQL queries.
- Handle exceptions: Errors can occur during database operations, so use
try-exceptblocks to handle them properly. - Transactions: To maintain data integrity, use transactions when necessary so multiple operations can be committed or rolled back as a single unit.
8. Summary
MySQL Connector/Python is a powerful tool for connecting to and working with MySQL databases using Python. In this article, we covered how to set up MySQL Connector/Python, perform basic database operations, use placeholders and prepared statements to improve security, and handle escaping and errors properly. By mastering these techniques, you can build database applications that are more efficient and secure.
As a next step, try exploring more practical examples and advanced database operations with MySQL Connector/Python. It is also important to use the official documentation and related resources to gain a deeper understanding of MySQL Connector/Python and make the most of its features.


