【问题标题】:Insert json data in table with Asyncpg using "executemany"使用 \"executemany\" 使用 Asyncpg 在表中插入 json 数据
【发布时间】:2022-12-09 01:20:11
【问题描述】:

我想用 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())

但我收到以下错误:

asyncpg.exceptions.DataError: invalid input in executemany() argument sequence element #0: expected a sequence, got dict

我试图将字典作为字符串传递。也有一个错误。

错误消息很清楚,代码与文档中的代码非常相似,
希望我要插入 json 数据。不幸的是,我没有看到我错过了什么。 有人发现问题/帮助我吗? 提前致谢。

【问题讨论】:

    标签: python postgresql asyncpg


    【解决方案1】:

    您需要将 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}',
            ],
        ]
    )
    

    【讨论】:

      猜你喜欢
      • 2022-11-24
      • 2014-09-30
      • 2019-05-02
      • 2016-03-27
      • 2019-07-10
      • 2019-10-17
      • 1970-01-01
      • 1970-01-01
      • 2021-07-19
      相关资源
      最近更新 更多