Rem*_*007 2 python postgresql asyncpg
我想使用 Asyncpg 在表中插入一些 json 数据(2 列: id 、 cluster_json )。我想使用“executemany”函数来加速插入过程。
我的代码:
async def main():
conn = await asyncpg.connect('postgresql://postgres:postgres@localhost:5432/postgres')
statement = '''INSERT INTO cluster(cluster_json) VALUES($1) '''
await conn.executemany(statement, [{"name":"John", "age":30, "car":null},
{"name":"John1", "age":31, "car":null}'])
await conn.close()
asyncio.get_event_loop().run_until_complete(main())
Run Code Online (Sandbox Code Playgroud)
但我收到以下错误:
asyncpg.exceptions.DataError: invalid input in executemany() argument sequence element #0: expected a sequence, got dict
Run Code Online (Sandbox Code Playgroud)
我试图将字典作为 str 传递。也有一个错误。
错误消息很清楚,代码与文档中的代码非常相似,
期望我想要插入 json 数据。不幸的是,我没有看到我错过了什么。有人发现问题/帮助我吗?提前致谢。
您需要将 JSON-blob 双重嵌套在列表中。第一个列表针对您要插入的每一行。第二个列表针对您想要传递给 SQL 语句的每个参数。asyncpg
不会尝试解析您的 SQL 语句。所以它不知道你只使用一个参数。因此,它需要您握住它的手,并给出该语句的所有参数的列表,即使该列表只有一个元素。
await conn.executemany(
statement,
[ # for first execution of statement
[ # first argument (i.e. $1) of first execution of statement
'{"name":"John", "age":30, "car": null}',
],
# for second execution of statement
[ # first argument (i.e. $1) of second execution of statement
'{"name":"John1", "age":31, "car": null}',
],
]
)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
820 次 |
最近记录: |