pymysql 查询结果转字典dict

28 篇文章 3 订阅
import pymysql

def get_db():
    # 打开数据库连接
    db = pymysql.connect(
        host="**.**.**.**", port=3306, user="root", passwd="1234567", db="my_db"
    )
    return db
 
def get_sql_conn():
    """
    获取数据库连接
    """
    db = get_db()
    cursor = db.cursor()
    return db,cursor
    
def get_index_dict(cursor):
    """
    获取数据库对应表中的字段名
    """
    index_dict=dict()
    index=0
    for desc in cursor.description:
        index_dict[desc[0]]=index
        index=index+1
    return index_dict
    
def 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 res


def 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

在这里插入图片描述

另外一个版本(优化了一下?)

import pymysql

def get_db():
    """
    获取数据库连接对象
    """
    # 打开数据库连接
    db = pymysql.connect(
        host="**.**.**.**", port=3306, user="root", passwd="1234567", db="my_db"
    )
    return db

def get_sql_conn():
    """
    获取数据库连接和游标对象
    """
    db = get_db()
    cursor = db.cursor()
    return db, cursor

def get_index_dict(cursor):
    """
    获取数据库对应表中的字段名和索引映射关系
    """
    index_dict = {}
    # 遍历游标对象的描述信息,获取字段名和索引的映射关系
    for index, desc in enumerate(cursor.description):
        index_dict[desc[0]] = index
    return index_dict

def get_dict_data_sql(cursor, sql):
    """
    执行SQL查询并将结果转化为字典格式的列表
    """
    cursor.execute(sql)
    data = cursor.fetchall()
    index_dict = get_index_dict(cursor)  # 获取字段名和索引的映射关系
    
    # 使用列表推导式和字典推导式来转化数据
    res = [
        {field_name: row[index_dict[field_name]] for field_name in index_dict}
        for row in data
    ]
    
    return res

def main():
    """
    主函数,执行查询并返回结果字典列表
    """
    with get_sql_conn() as (db, cursor):
        sql = "SELECT * FROM `My_table` WHERE `in_using`='1' LIMIT 10;"
        res_dict = get_dict_data_sql(cursor, sql)
    return res_dict

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值