Python > Working with Data > Databases > Connecting to Relational Databases (e.g., PostgreSQL, MySQL) with libraries like `psycopg2`, `mysql.connector`
Connecting to MySQL using mysql.connector
This snippet illustrates how to connect to a MySQL database using the mysql.connector
library in Python. It includes setting up the connection, executing basic queries, and properly closing the connection.
Prerequisites
Before running this code, ensure you have the following:
mysql-connector-python
library installed (pip install mysql-connector-python
).
Code Snippet
This code defines a dictionary db_params
holding the connection details. It connects to the database using mysql.connector.connect()
. A cursor object is created for executing SQL. A SELECT
query is executed to retrieve the MySQL version. Finally, the cursor and connection are closed in a finally
block to release resources.
import mysql.connector
db_params = {
'host': 'localhost',
'database': 'your_database',
'user': 'your_user',
'password': 'your_password'
}
conn = None # Initialize conn to None
cur = None # Initialize cur to None
try:
# Establish a connection to the MySQL database
conn = mysql.connector.connect(**db_params)
# Create a cursor object to execute SQL queries
cur = conn.cursor()
# Execute a simple query
cur.execute('SELECT VERSION()')
# Fetch the result
db_version = cur.fetchone()
print(f'MySQL database version: {db_version}')
# Commit the changes (if any)
conn.commit()
except mysql.connector.Error as err:
print(f'Error connecting to MySQL: {err}')
if conn:
conn.rollback()
finally:
# Close the cursor and connection
if cur:
cur.close()
if conn:
conn.close()
print('Connection closed.')
Concepts Behind the Snippet
This snippet demonstrates the key steps in connecting to a MySQL database:
commit()
and rollback()
to ensure data consistency.
Real-Life Use Case
This code is applicable in scenarios like:
For instance, a content management system (CMS) might use this code to store articles, user accounts, and settings in a MySQL database.
Best Practices
try...except
blocks.with
statement) for automatic resource cleanup.
When to Use Them
Use this connection method when you need to access a MySQL database from your Python application. It's suitable for applications requiring persistent data storage and retrieval using MySQL.
Alternatives
Alternatives to mysql.connector
include:
Pros
mysql.connector
is a pure Python implementation, making it platform-independent.
Cons
FAQ
-
How can I prevent SQL injection attacks?
Use parameterized queries or prepared statements. Pass data separately from the SQL query. Themysql.connector
library supports parameterization when using the cursor'sexecute()
method. -
What is the difference between
mysql.connector
andPyMySQL
?
mysql.connector
is the official MySQL driver written in pure Python.PyMySQL
is another popular option, also written in pure Python. They have similar functionalities but may differ in performance and specific features. Choose based on project requirements and preferences.