本文主要是介绍pymysql 查询结果转字典dict,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
import pymysqldef get_db():# 打开数据库连接db = pymysql.connect(host="**.**.**.**", port=3306, user="root", passwd="1234567", db="my_db")return dbdef get_sql_conn():"""获取数据库连接"""db = get_db()cursor = db.cursor()return db,cursordef get_index_dict(cursor):"""获取数据库对应表中的字段名"""index_dict=dict()index=0for desc in cursor.description:index_dict[desc[0]]=indexindex=index+1return index_dictdef get_dict_data_sql(cursor,sql):"""运行sql语句,获取结果,并根据表中字段名,转化成dict格式(默认是tuple格式)"""cursor.execute(sql)data=cursor.fetchall()index_dict=get_index_dict(cursor)res=[]for datai in data:resi=dict()for indexi in index_dict:resi[indexi]=datai[index_dict[indexi]]res.append(resi)return resdef main():db,cursor = get_sql_conn()sql = "SELECT * FROM `My_table` WHERE `in_using`='1' limit 10;"res_dict = get_dict_data_sql(cursor, sql)return res_dict
这篇关于pymysql 查询结果转字典dict的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!