2.aiopg返回结果变为字典类型


aiopg返回结果变为python字典

import aiopg
import asyncio

dsn = 'dbname=aiopg user=aiopg password=passwd host=127.0.0.1 port=5432'

async def run():
    async with aiopg.create_pool(dsn) as pool:
        async with pool.acquire() as conn:
            async with conn.cursor() as cur:
                await cur.execute("SELECT city,prcp FROM weather;")
                # 获取字段名
                res = cur.description
                columns_name = [i[0] for i in res]
                print(columns_name)  # ['city', 'prcp']
                res = await cur.fetchall()
                res_dict = [dict(zip(columns_name, row_value)) for row_value in res]
                print(res_dict)
                # [{'city': 'San Francisco', 'prcp': 0.25}, {'city': 'San Francisco', 'prcp': 0.15},...]

asyncio.run(run())

相关