【问题标题】:How do I get the “id” after INSERT into a postgres database with Python?如何使用 Python 将“id”插入到 postgres 数据库中?
【发布时间】:2016-11-23 11:39:59
【问题描述】:

我正在对 postgres 数据库进行 INSERT,该数据库有一个名为 id 的自动增量字段。

在 Python 中插入后如何获取 id 的值?这个站点上有关于 MySQL 数据库的很好的参考(即使用 cursor.lastrowid 或 connection.insert_id()),但这些似乎不适用于我的 postgres 数据库。

id 字段正在使用一个序列来自动递增。所以id字段不为null,默认,nextval('table_id_seq')

谢谢

【问题讨论】:

标签: python postgresql


【解决方案1】:

请尝试一下:

cursor.execute("INSERT INTO .... RETURNING
id_of_new_row = cursor.fetchone()[0]

【讨论】:

    猜你喜欢
    • 2020-09-03
    • 1970-01-01
    • 2020-11-07
    • 1970-01-01
    • 1970-01-01
    • 2021-07-19
    • 2017-05-20
    • 1970-01-01
    • 2017-04-20
    相关资源
    最近更新 更多