python 操作mysql数据中fetchone()和fetchall()方式


当前第2页 返回上一页

先测试SQL:

代码:

import pymysql
import pandas as pd
 
conn = pymysql.Connect(host="127.0.0.1",port=3306,user="root",password="123456",charset="utf8",db="sql_prac")
 
cur = conn.cursor()
print("连接成功")
sql = "select count(case when type_code in ('ys4ng35toofdviy9ce0pn1uxw2x7trjb','娱乐') then 1 end) 娱乐," \
  "count(case when type_code in ('vekgqjtw3ax20udsniycjv1hdsa7t4oz','经济') then 1 end) 经济," \
  "count(case when type_code in ('vjzy0fobzgxkcnlbrsduhp47f8pxcoaj','军事') then 1 end) 军事," \
  "count(case when type_code in ('uamwbfqlxo7bu0warx6vkhefigkhtoz3' ,'政治') then 1 end) 政治," \
  "count(case when type_code in ('lyr1hbrnmg9qzvwuzlk5fas7v628jiqx','文化') then 1 end) 文化 from test"
cur.execute(sql)
res = cur.fetchone()
print(res)

返回结果为元组:

(10, 6, 4, 4, 2)

data = [
    {"name": "娱乐", "value": res[0]},
    {"name": "经济", "value": res[1]},
    {"name": "军事", "value": res[2]},
    {"name": "政治", "value": res[3]},
    {"name": "文化", "value": res[4]}
]
result = sorted(data, key=lambda x: x['value'], reverse=True)
print(result)

结果和 cur.fetchall返回的结果经过处理后,结果是一样的:

[{'name': '娱乐', 'value': 10}, {'name': '经济', 'value': 6}, {'name': '军事', 'value': 4}, {'name': '政治', 'value': 4}, {'name': '文化', 'value': 2}]

以上这篇python 操作mysql数据中fetchone()和fetchall()方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。


打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...