MySQL Python Connection and Usage
MySQL is one of the most popular open-source relational databases, and Python is one of today's most popular programming languages. Combining Python with MySQL allows us to easily develop database-driven applications.
This article will introduce in detail how to connect to and operate MySQL databases using Python, covering the following:
- How to install the MySQL Python driver
- Establish and close database connections
- Execute various SQL queries
- Transaction management and error handling
- Best practices for database operations
Preparation
Install necessary software
Before you begin, please make sure you have installed the following software:
- Python (3.6 or higher recommended)
- MySQL Server (Community edition is sufficient)
- MySQL Connector/Python (MySQL driver for Python)
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 a basic connection
The following is how to use mysql-connector-python Basic code for establishing a database connection:
Example
import
mysql.
connector
Creating a Database Connection
db
=
mysql.
connector
.
connect
(
host
=
"localhost"
,
user
=
"yourusername"
,
password
=
"yourpassword"
,
database
=
"yourdatabase"
)
(
"Database connection successful!"
)
Connection parameter descriptions
host: MySQL server address (locally "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
import
pymysql
Creating a Database Connection
db
=
pymysql.
connect
(
host
=
"localhost"
,
user
=
"yourusername"
,
password
=
"yourpassword"
,
database
=
"yourdatabase"
)
(
"Database connection successful!"
)
Executes an SQL query
Create a cursor object
Before executing SQL statements, we need to create a cursor object:
Example
cursor
=
db.
cursor
(
)
Execute a SELECT query
Example
cursor.
execute
(
"SELECT * FROM your_table"
)
Fetch all results
results
=
cursor.
fetchall
(
)
for
row
in
results:
(
row
)
Execute INSERT, UPDATE, DELETE operations
Example
Insert data
sql
=
"INSERT INTO users (name, age) VALUES (%s, %s)"
values
=
(
"Zhang San"
,
25
)
cursor.
execute
(
sql
,
values
)
Commit a transaction
db.
commit
(
)
(
cursor.
rowcount
,
" records inserted successfully"
)
Use parameterized queries
To prevent SQL injection, you should always use parameterized queries:
Example
sql
=
"SELECT * FROM users WHERE name = %s"
name
=
(
"Zhang San"
,
)
cursor.
execute
(
sql
,
name
)
Transaction management
Basic concepts of transactions
A MySQL transaction is a set of atomic SQL queries that either all execute successfully or none execute.
Using transactions
Example
try
:
Start a 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 a transaction
db.
commit
(
)
(
"Transaction executed successfully"
)
except
Exception
as
e:
If an error occurs, roll back the transaction
db.
rollback
(
)
(
"Transaction failed:"
,
e
)
Error handling
Catch database errors
Example
try
:
cursor.
execute
(
"SELECT * FROM non_existent_table"
)
except
mysql.
connector
.
Error
as
err:
(
"Database error:"
,
err
)
Common error codes
1045: Access denied (wrong username or password)1049: Unknown database1146: Table does not exist1062: Duplicate key value
Close the Connection
Close the connection properly
After completing database operations, you should close the cursor and connection:
Example
cursor.
close
(
)
db.
close
(
)
(
"Database connection closed"
)
Using the with statement
Python's with statement can automatically manage resources:
Example
with
mysql.
connector
.
connect
(
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:
(
row
)
The connection is automatically closed 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
from
mysql.
connector
import
pooling
Create a connection pool
db_pool
=
pooling.
MySQLConnectionPool
(
pool_name
=
"mypool"
,
pool_size
=
5
,
host
=
"localhost"
,
user
=
"yourusername"
,
password
=
"yourpassword"
,
database
=
"yourdatabase"
)
Get a 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.