Python 操作mysql数据库查询之fetchone(), fetchmany(), fetchall()用法示例
作者:houyanhua1 时间:2023-07-09 00:11:24
本文实例讲述了Python 操作mysql数据库查询之fetchone(), fetchmany(), fetchall()用法。分享给大家供大家参考,具体如下:
demo.py(查询,取出一条数据,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):
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程序设计有所帮助。
来源:https://blog.csdn.net/houyanhua1/article/details/84773055
标签:Python,mysql,数据库查询


猜你喜欢
python操作数据库之sqlite3打开数据库、删除、修改示例
2024-01-26 15:47:01
MySQL 删除数据库中重复数据方法小结
2024-01-25 16:39:03

Python学习之装饰器与类的装饰器详解
2023-11-23 20:04:07
浅谈怎么给Python添加类型标注
2023-11-21 05:16:17

JS+CSS实现闪烁字体效果代码
2024-04-18 09:31:04
举例讲解Python中的死锁、可重入锁和互斥锁
2023-12-21 07:35:03
Python自定义scrapy中间模块避免重复采集的方法
2022-02-19 13:32:44
mysql中的int(10)int(20)分别代表什么意思
2024-01-20 21:31:30
Python检查 云备份进程是否正常运行代码实例
2023-07-08 23:59:05
Python必须了解的35个关键词
2023-05-20 07:37:33
利用python实现查看溧阳的摄影圈
2021-09-05 21:33:16

Python 实现自动化Excel报表的步骤
2022-12-01 10:49:29

Python计算机视觉里的IOU计算实例
2021-12-07 18:15:10
python创建学生成绩管理系统
2023-08-09 04:19:38

浅析SQL Server 聚焦索引对非聚集索引的影响
2024-01-16 19:19:44

Keras 加载已经训练好的模型进行预测操作
2021-07-04 15:15:10
Python中的startswith和endswith函数使用实例
2022-06-19 00:47:55
python实现扫雷小游戏
2023-02-15 11:58:58

如何使用scrapy中的ItemLoader提取数据
2021-01-10 07:02:06

python列表切片和嵌套列表取值操作详解
2021-07-23 21:54:30