Python3 MySQL (PyMySQL) 使用指南
引言
Python 是一种广泛应用于各种开发场景的编程语言,而 MySQL 则是一款流行的关系型数据库管理系统。PyMySQL 是一个纯 Python 实现的 MySQL 客户端库,它提供了丰富的接口和功能,使得 Python 程序员可以轻松地与 MySQL 数据库进行交互。本文将详细介绍 PyMySQL 的安装、配置和使用方法。
安装 PyMySQL
首先,您需要安装 PyMySQL。可以通过以下命令进行安装:
bash
pip install PyMySQL
连接 MySQL 数据库
在使用 PyMySQL 之前,您需要先建立与 MySQL 数据库的连接。以下是一个简单的示例:
python
import pymysql
# 连接数据库
connection = pymysql.connect(host='localhost',
user='your_username',
password='your_password',
database='your_database',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
# 执行 SQL 查询语句
sql = "SELECT `user_id`, `user_name` FROM `users`"
cursor.execute(sql)
# 获取所有记录列表
results = cursor.fetchall()
for row in results:
print(f"User ID: {row['user_id']}, User Name: {row['user_name']}")
finally:
connection.close()
在上面的代码中,我们首先导入了 pymysql 库,然后创建了一个 pymysql.connect() 对象来建立与 MySQL 数据库的连接。其中,host、user、password 和 database 分别代表数据库的主机地址、用户名、密码和数据库名称。charset 参数用于指定连接字符集,cursorclass 参数用于指定游标类型。
执行 SQL 语句
PyMySQL 提供了丰富的接口来执行 SQL 语句。以下是一些常用的 SQL 语句及其对应的 PyMySQL 接口:
- 查询语句:
python
with connection.cursor() as cursor:
cursor.execute("SELECT * FROM `users`")
results = cursor.fetchall()
for row in results:
print(row)
- 插入语句:
python
with connection.cursor() as cursor:
cursor.execute("INSERT INTO `users` (`user_name`, `user_age`) VALUES (%s, %s)", ('John Doe', 28))
connection.commit()
- 更新语句:
python
with connection.cursor() as cursor:
cursor.execute("UPDATE `users` SET `user_age` = %s WHERE `user_name` = %s", (30, 'John Doe'))
connection.commit()
- 删除语句:
python
with connection.cursor() as cursor:
cursor.execute("DELETE FROM `users` WHERE `user_name` = %s", ('John Doe',))
connection.commit()
使用事务
在执行一系列 SQL 语句时,您可能需要使用事务来确保数据的完整性。以下是如何在 PyMySQL 中使用事务的示例:
python
with connection.cursor() as cursor:
try:
# 开始事务
connection.begin()
# 执行多个 SQL 语句
cursor.execute("INSERT INTO `users` (`user_name`, `user_age`) VALUES (%s, %s)", ('Jane Doe', 25))
cursor.execute("UPDATE `users` SET `user_age` = %s WHERE `user_name` = %s", (31, 'John Doe'))
# 提交事务
connection.commit()
except Exception as e:
# 回滚事务
connection.rollback()
print(f"An error occurred: {e}")
总结
PyMySQL 是一个功能强大的 Python MySQL 客户端库,可以帮助您轻松地与 MySQL 数据库进行交互。本文介绍了 PyMySQL 的安装、配置和使用方法,包括连接数据库、执行 SQL 语句和事务处理等。希望本文能帮助您更好地了解和使用 PyMySQL。