Python 操作 MySQL 数据库
文章目录
一、概述
Python通过pymysql库可以方便地操作MySQL数据库,实现数据查询、插入、更新和删除等操作。pymysql是一个纯Python实现的MySQL客户端库,支持Python 3.x版本。
- pymysql 库安装:
pip install pymysql
二、基本连接与游标操作
1. 数据库连接
import pymysql # 建立数据库连接 connect = pymysql.connect( host="master",# 数据库主机地址 user="root",# 数据库用户名 password="123456",# 数据库密码 database="stu",# 要使用的数据库名 port=3306# 端口号,MySQL默认3306)参数说明:
host: MySQL服务器地址,可以是IP或域名user: 登录用户名password: 登录密码database: 要操作的数据库port: 端口号,默认3306
2. 创建游标
cursor = connect.cursor()- 游标用于执行SQL语句并获取结果,是数据库操作的核心对象。
三、SQL语句执行方式
1. 字符串拼接方式(不推荐)
name ="zhouqi" balance =1500 ids ="20250101 OR 1=1"# 存在SQL注入风险 stu_id ="20251001"# 第一种写法:字符串直接拼接 query_sql ="select * from students where stu_id = "+f"{ids}"# 或使用格式化字符串# query_sql = "select * from students where stu_id = %s" % idsprint(query_sql)# 输出:select * from students where stu_id = 20250101 OR 1=1 cursor.execute(query_sql)注意:这种方式存在SQL注入风险,当用户输入包含SQL语句时(如OR 1=1),可能导致数据泄露。
2. 参数化查询方式(推荐)
# 第二种写法:使用参数化查询 query_sql ="insert into account values(0,%s,%s)"print(query_sql)# 输出:insert into account values(0,%s,%s) cursor.execute(query_sql,(name, balance))优势:
- 防止SQL注入攻击
- 自动处理数据类型转换
- 提高代码可读性
3. 批量插入数据
# 一次性插入多条数据 name_list =[("liuba",2000),("hongjiu",3000)] cursor.executemany(query_sql, name_list)executemany()方法可以高效地批量执行相同的SQL语句,参数为元组列表(即使参数为一个也需要使用元组)。
四、事务管理与结果获取
1. 提交事务
# 提交事务,将更改更新到表 connect.commit()注意:对于INSERT、UPDATE、DELETE等修改操作,必须调用commit()才会生效。
2. 结果集获取
# 获取单条记录 cursor.execute("SELECT * FROM students")print(cursor.fetchone())# 获取第一条记录print("*"*50)# 获取所有记录print(cursor.fetchall())# 获取所有记录print("*"*50)# 获取指定数量的记录print(cursor.fetchmany(10))# 获取10条记录方法:
fetchone(): 获取下一行记录fetchall(): 获取所有剩余记录fetchmany(size): 获取指定数量的记录,为-1时获取全部记录
五、使用 with (上下文管理器)优化代码
1. 文件读取与数据处理
import pymysql withopen(r"D:\Desktop\mysqlmd\第四天\socres.txt","r", encoding="utf-8")as fp: line_list = fp.readlines()print(line_list) tuple_list =[]for line in line_list: li = line.strip().split(",") tuple_list.append((int(li[0]),int(li[1]),int(li[2]),str(li[3])))print(tuple_list)2. 使用with语句自动管理资源
# with语句自动管理连接和游标的关闭with pymysql.connect( host="master", user="root", password="123456", database="stu", port=3306)as connnet:with connnet.cursor()as cursor: insert_sql ="insert into score values(%s,%s,%s,%s)"try: cursor.executemany(insert_sql, tuple_list)except Exception as e:print(e) connnet.rollback()# 发生异常时回滚事务else: connnet.commit()# 正常执行时提交事务优势:
- 自动关闭连接和游标,避免资源泄漏
- 代码结构更清晰