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 LIMIT 2;")
# 获取字段名
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())
[{'city': 'San Francisco', 'prcp': 0.25}, {'city': 'San Francisco', 'prcp': 0.15}]
方法二
使用
cursor_factory=psycopg2.extras.RealDictCursor
设置
import aiopg
import psycopg2
import asyncio
dsn = 'dbname=aiopg user=aiopg password=passwd host=127.0.0.1 port=5432'
async def go():
conn = await aiopg.connect(dsn)
cur = await conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
await cur.execute("SELECT city,prcp FROM weather LIMIT 2;")
res = await cur.fetchall()
print(res)
for i in res:
print(i.get('city'))
cur.close()
conn.close()
if __name__ == "__main__":
asyncio.run(go())
[RealDictRow([('city', 'San Francisco'), ('prcp', 0.25)]), RealDictRow([('city', 'San Francisco'), ('prcp', 0.15)])]
San Francisco
San Francisco