Python 3.6 使用 PyMySQL 操作 MySQL 数据库完整指南
本文详细介绍如何在 Python 3.6 环境中使用 PyMySQL 库连接并操作 MySQL 数据库。内容涵盖库的安装方法,以及通过具体代码实例演示如何建立连接、创建游标、执行查询、插入数据、提交事务及关闭连接等核心步骤,帮助开发者快速掌握 Python 与 MySQL 的交互技巧。
本文分享了基于 Python 3.6 版本操作 MySQL 数据库的具体实现方法,供读者参考学习。
首先需要安装 PyMySQL 库。
具体的安装与使用细节可参考官方 GitHub 仓库:https://github.com/PyMySQL/PyMySQL/。
pip install pymsql
以下是第一个代码示例,演示如何建立数据库连接并执行查询操作。
import pymysql
# 创建连接
# 参数依次对应服务器地址,用户名,密码,数据库
conn = pymysql.connect(host='127.0.0.1', user='root', passwd='123456', db='demo')
# 创建游标
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 执行语句返回影响的行数
effect_row = cursor.execute("select * from course")
print(effect_row)
# 获取所有数据
result = cursor.fetchall()
result = cursor.fetchone() # 获取下一个数据
result = cursor.fetchone() # 获取下一个数据(在上一个的基础之上)
# cursor.scroll(-1, mode='relative') # 相对位置移动
# cursor.scroll(0,mode='absolute') # 绝对位置移动
# 提交,不然无法保存新建或者修改的数据
conn.commit()
# 关闭游标
cursor.close()
# 关闭连接
conn.close()
第二个示例展示了如何向数据库中插入单条数据。
import pymysql
# 建立连接
conn = pymysql.connect(host='127.0.0.1', user='root', passwd='123456', db='demo')
# 创建游标
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 插入一条数据 %s是占位符 占位符之间用逗号隔开
effect_row = cursor.execute("insert into course(cou_name,time) values(%s,%s)", ("Engilsh", 100))
print(effect_row)
conn.commit()
cursor.close()
conn.close()
第三个示例提供了更完整的上下文管理方式,包括使用 try-finally 结构处理连接、插入记录以及查询记录的完整流程。
import pymysql.cursors
# Connect to the database
connection = pymysql.connect(host='localhost',
user='user',
password='passwd',
db='db',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
# Create a new record
sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
cursor.execute(sql, ('webmaster@python.org', 'very-secret'))
# connection is not autocommit by default. So you must commit to save
# your changes.
connection.commit()
with connection.cursor() as cursor:
# Read a single record
sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
cursor.execute(sql, ('webmaster@python.org',))
result = cursor.fetchone()
print(result)
finally:
connection.close()
以上内容即为 Python 操作 MySQL 数据库的主要实现方式,希望能为读者的学习提供有益帮助,也欢迎大家继续支持本站获取更多技术资源。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













