Bootstrap

pymysql 查询结果转字典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=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

;