Python MySQL查询结果获取:fetchone、fetchmany与fetchall详解
本文介绍Python中使用PyMySQL连接MySQL数据库时,如何获取查询结果。通过示例代码演示fetchone()获取单条记录、fetchmany()获取指定数量记录以及fetchall()获取所有记录的方法,包含完整的连接、执行与关闭资源代码。
Python MySQL查询结果获取方法概述
本文详细介绍Python操作MySQL数据库时,利用fetchone()、fetchmany()和fetchall()方法获取查询结果的用法。内容包含具体示例,供读者参考学习。
以下demo.py代码演示如何查询并获取单条数据,主要使用fetchone()方法。
获取单条数据:fetchone()示例
from pymysql import *
def main():
# 创建Connection连接
conn = connect(host='localhost',port=3306,user='root',password='mysql',database='jing_dong',charset='utf8')
# 获得Cursor对象
cs1 = conn.cursor()
# 执行select语句,并返回受影响的行数:查询一条数据
count = cs1.execute('select id,name from goods where id>=4')
# 打印受影响的行数
print("查询到%d条数据:" % count)
for i in range(count):
# 获取查询的结果
result = cs1.fetchone()
# 打印查询的结果
print(result) # 元组 (1, '张三', 20, '男')
# 获取查询的结果
# 关闭Cursor对象
cs1.close()
conn.close()
if __name__ == '__main__':
main()
以下demo.py代码演示如何查询并获取多条数据,分别展示fetchmany()和fetchall()的用法。
获取多条数据:fetchmany()与fetchall()示例
from pymysql import *
def main():
# 创建Connection连接
conn = connect(host='localhost',port=3306,user='root',password='mysql',database='jing_dong',charset='utf8')
# 获得Cursor对象
cs1 = conn.cursor()
# 执行select语句,并返回受影响的行数:查询一条数据
count = cs1.execute('select id,name from goods where id>=4')
# 打印受影响的行数
print("查询到%d条数据:" % count)
# for i in range(count):
# # 获取查询的结果
# result = cs1.fetchone() # 取出一条记录,返回元组。
# # 打印查询的结果
# print(result)
# # 获取查询的结果
# 获取所有记录
result = cs1.fetchall() # fetchmany(3) 取出3条记录,返回二维元组。
print(result) # 二维元组
# 关闭Cursor对象
cs1.close()
conn.close()
if __name__ == '__main__':
main()
如需了解更多Python相关知识,可参考本站《Python常见数据库操作技巧汇总》、《Python数学运算技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》等专题。
希望上述内容对您的Python编程有所帮助。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









