MySQL Python Connection and Usage
MySQL is one of the most popular open-source relational databases, and Python is one of the most popular programming languages today. Combining Python with MySQL allows us to easily develop database-driven applications.
This article will detail how to use Python to connect to and operate a MySQL database, covering the following:
- How to install the MySQL Python driver
- Establishing and closing database connections
- Executing various SQL queries
- Transaction management and error handling
- Best practices for database operations
Preparation
Install Required Software
Before you begin, please ensure you have installed the following software:
- Python(Recommended 3.6 or higher)
- MySQL Server(Community Edition is sufficient)
- MySQL Connector/Python(Python's MySQL driver)
Install MySQL Connector/Python
You can install the official MySQL Python driver via pip:
pip install mysql-connector-python
Or install PyMySQL (another popular MySQL Python driver):
pip install pymysql
Connect to MySQL Database
Establish Basic Connection
The following is usingmysql-connector-pythonBasic code for establishing a database connection:
Example
# Create database connection
db = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
print("Database connection successful!")
Connection Parameter Explanation
host: MySQL server address (local is "localhost")user: Database usernamepassword: User passworddatabase: Name of the database to connect to (optional)
Connect Using PyMySQL
If you choose to use PyMySQL, the connection method is slightly different:
Example
# Create database connection
db = pymysql.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
print("Database connection successful!")
Execute SQL Queries
Create Cursor Object
Before executing SQL statements, we need to create a cursor object:
Example
Execute SELECT Query
Example
# Fetch all results
results = cursor.fetchall()
for row in results:
print(row)
Execute INSERT, UPDATE, DELETE Operations
Example
sql = "INSERT INTO users (name, age) VALUES (%s, %s)"
values = ("Zhang San", 25)
cursor.execute(sql, values)
# Commit transaction
db.commit()
print(cursor.rowcount, " record(s) inserted successfully")
Use Parameterized Queries
To prevent SQL injection, you should always use parameterized queries:
Example
name = ("Zhang San",)
cursor.execute(sql, name)
Transaction Management
Basic Concepts of Transactions
A MySQL transaction is a group of atomic SQL queries, where either all execute successfully or none execute at all.
Using Transactions
Example
# Begin transaction
cursor.execute("START TRANSACTION")
# Execute multiple SQL statements
cursor.execute("UPDATE accounts SET balance = balance - 100 WHERE id = 1")
cursor.execute("UPDATE accounts SET balance = balance + 100 WHERE id = 2")
# Commit transaction
db.commit()
print("Transaction executed successfully")
except Exception as e:
# An error occurred, roll back the transaction
db.rollback()
print("Transaction execution failed:", e)
Error Handling
Catching Database Errors
Example
cursor.execute("SELECT * FROM non_existent_table")
except mysql.connector.Error as err:
print("Database error:", err)
Common Error Codes
1045: Access denied (incorrect username or password)1049: Unknown database1146: Table does not exist1062: Duplicate key value
Closing Connections
Properly Closing Connections
After completing database operations, you should close the cursor and connection:
Example
db.close()
print("Database connection closed")
Using the with Statement
Python'swithstatement can automatically manage resources:
Example
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
) as db:
with db.cursor() as cursor:
cursor.execute("SELECT * FROM users")
results = cursor.fetchall()
for row in results:
print(row)
# The connection will automatically close after leaving the with block
Best Practices
Connection Pool
For applications that frequently connect to the database, it is recommended to use a connection pool:
Example
# Create connection pool
db_pool = pooling.MySQLConnectionPool(
pool_name="mypool",
pool_size=5,
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
# Get connection from the connection pool
db = db_pool.get_connection()
ORM Framework
For complex applications, you can consider using an ORM (Object-Relational Mapping) framework, such as SQLAlchemy or Django ORM.
Other Extensions