PyMySQL:一个MySQL操作的完美助手!
大家好!今天我要和大家分享一个特别实用的Python库 – PyMySQL。它是一个纯Python实现的MySQL客户端库,让我们能够在Python程序中轻松操作MySQL数据库。不管是简单的数据查询,还是复杂的数据库操作,PyMySQL都能帮我们轻松搞定。它就像是一个贴心的数据库管家,帮我们打理好所有数据库相关的事务!
PyMySQL是什么?
PyMySQL是一个用Python写的MySQL客户端库。听起来很专业?其实很简单,你可以把它想象成一个翻译官,它帮助Python程序和MySQL数据库之间进行”对话”。通过它,我们可以用Python代码来操作MySQL数据库。
安装PyMySQL
首先,让我们安装PyMySQL:
pip install PyMySQL
建立数据库连接
让我们先来看看如何连接数据库:
import pymysql
# 建立连接
conn = pymysql.connect(
host='localhost', # 数据库主机地址
port=3306, # 端口号,默认3306
user='root', # 用户名
password='123456', # 密码
database='test_db' # 数据库名
)
# 创建游标对象
cursor = conn.cursor()
# 使用完后记得关闭连接
conn.close()
小贴士:建议使用with语句来自动管理数据库连接,这样更安全也更简洁!
基本数据库操作1. 创建表
来创建一个简单的学生信息表:
import pymysql
with pymysql.connect(host='localhost', user='root',
password='123456', database='test_db') as conn:
with conn.cursor() as cursor:
# 创建表
sql = """
CREATE TABLE IF NOT EXISTS students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
age INT,
score FLOAT
)
"""
cursor.execute(sql)
conn.commit() # 提交更改
2. 插入数据
def insert_student(name, age, score):
with pymysql.connect(host='localhost', user='root',
password='123456', database='test_db') as conn:
with conn.cursor() as cursor:
sql = "INSERT INTO students (name, age, score) VALUES (%s, %s, %s)"
try:
cursor.execute(sql, (name, age, score))
conn.commit()
print(f"成功插入学生:{name}")
except Exception as e:
print(f"插入失败:{e}")
conn.rollback() # 发生错误时回滚
# 使用函数
insert_student("小明", 18, 95.5)
注意事项:始终使用参数化查询来防止SQL注入攻击!
3. 查询数据
def query_students(min_score=0):
with pymysql.connect(host='localhost', user='root',
password='123456', database='test_db') as conn:
with conn.cursor(pymysql.cursors.DictCursor) as cursor: # 返回字典格式的结果
sql = "SELECT * FROM students WHERE score > %s"
cursor.execute(sql, (min_score,))
results = cursor.fetchall() # 获取所有结果
return results
# 查询成绩大于90的学生
high_score_students = query_students(90)
for student in high_score_students:
print(f"姓名:{student['name']}, 成绩:{student['score']}")
进阶操作1. 批量插入数据
def batch_insert_students(students_list):
with pymysql.connect(host='localhost', user='root',
password='123456', database='test_db') as conn:
with conn.cursor() as cursor:
sql = "INSERT INTO students (name, age, score) VALUES (%s, %s, %s)"
try:
cursor.executemany(sql, students_list)
conn.commit()
print(f"成功插入{cursor.rowcount}条记录")
except Exception as e:
print(f"插入失败:{e}")
conn.rollback()
# 批量插入示例
students = [
("小红", 17, 88.5),
("小张", 18, 92.0),
("小李", 19, 85.5),
]
batch_insert_students(students)
2. 事务处理
def transfer_score(from_student, to_student, points):
with pymysql.connect(host='localhost', user='root',
password='123456', database='test_db') as conn:
try:
with conn.cursor() as cursor:
# 开始事务
conn.begin()
# 减少一个学生的分数
sql1 = "UPDATE students SET score = score - %s WHERE name = %s"
cursor.execute(sql1, (points, from_student))
# 增加另一个学生的分数
sql2 = "UPDATE students SET score = score + %s WHERE name = %s"
cursor.execute(sql2, (points, to_student))
# 提交事务
conn.commit()
print("转移分数成功!")
except Exception as e:
conn.rollback() # 发生错误时回滚
print(f"转移分数失败:{e}")
实用技巧
使用连接池:
from pymysql.cursors import DictCursor
from DBUtils.PooledDB import PooledDB
# 创建连接池
pool = PooledDB(
creator=pymysql, # 使用pymysql创建连接
maxconnections=6, # 连接池最大连接数
mincached=2, # 初始化时,最小的空闲连接数
host='localhost',
user='root',
password='123456',
database='test_db',
cursorclass=DictCursor
)
# 从连接池获取连接
conn = pool.connection()
处理BLOB数据:
def save_image(student_id, image_path):
with open(image_path, 'rb') as f:
image_data = f.read()
with pymysql.connect(host='localhost', user='root',
password='123456', database='test_db') as conn:
with conn.cursor() as cursor:
sql = "UPDATE students SET photo=%s WHERE id=%s"
cursor.execute(sql, (image_data, student_id))
conn.commit()
练习任务
创建一个图书管理系统的数据库,包含图书和借阅记录表
实现图书借阅和归还功能,使用事务确保数据一致性
编写一个简单的学生成绩统计系统
实现数据的导入导出功能
总结
今天我们学习了PyMySQL的核心知识:
关键要点:
始终使用参数化查询防止SQL注入
正确管理数据库连接和事务
使用连接池提高性能
适当的错误处理和回滚机制
PyMySQL虽然看起来内容不少,但它的使用逻辑其实很清晰。建议大家从简单的查询开始,逐步尝试更复杂的操作。记住:多写代码,多思考,数据库操作很快就能掌握!
下期我们将探讨更多数据库优化和高级查询技巧。记得点赞关注,我们下期见!