【问题标题】:How to return the Primary Key of the newly inserted row using asyncpg?如何使用 asyncpg 返回新插入行的主键?
【发布时间】:2018-04-18 00:47:14
【问题描述】:

我想做这样的事情:

    async with app.pg_pool.acquire() as pg:
        uid = await pg.execute('INSERT INTO users (created, keyed, key, email) '
                               'VALUES ($1, $2, $3, $4) RETURNING id',
                               time, time, key, rj['email'])['id']

但是Connection.execute 似乎除了状态之外没有返回任何东西:

https://magicstack.github.io/asyncpg/current/api/index.html?highlight=returning#asyncpg.connection.Connection.execute

问题也可以表述为:使用 asyncpg 时如何获取 RETURNING 语句的响应?

【问题讨论】:

    标签: asyncpg


    【解决方案1】:

    只需使用Connection.fetchval() 而不是execute()

    【讨论】:

      【解决方案2】:

      Connection.execute 将返回 INSERT 的状态。如果您需要 Record、Records 或 Value,请使用以下选项之一,而不是 Connection.execute

      1. Connection.fetchval - 仅返回指定字段的值。如果未指定任何字段,则返回 null
      2. Connection.fetch - 将返回 dict 的数组。每个 dict 都将具有在 RETURNING 语句之后指定的字段列表。
      3. Connection.fetchrow - 将返回一个 dict,其中包含在 RETURNING 语句之后指定的字段列表

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-21
        • 2012-01-18
        • 1970-01-01
        • 2021-05-13
        • 2010-10-22
        • 2017-11-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多