Python/postgres/psycopg2:获取刚刚插入的行的ID

发布于 2024-10-21 15:12:00 字数 875 浏览 2 评论 0原文

我正在使用 Python 和 psycopg2 来连接 postgres。

当我插入一行时...

sql_string = "INSERT INTO hundred (name,name_slug,status) VALUES ("
sql_string += hundred_name + ", '" + hundred_slug + "', " + status + ");"
cursor.execute(sql_string)

...如何获取刚刚插入的行的 ID?尝试:

hundred = cursor.fetchall() 

返回错误,而使用RETURNING id

sql_string = "INSERT INTO domes_hundred (name,name_slug,status) VALUES ("
sql_string += hundred_name + ", '" + hundred_slug + "', " + status + ") RETURNING id;"
hundred = cursor.execute(sql_string)

仅返回None

更新: currval 也是如此(即使直接在 postgres 中使用此命令也可以):

sql_string = "SELECT currval(pg_get_serial_sequence('hundred', 'id'));"
hundred_id = cursor.execute(sql_string)

任何人都可以建议吗?

谢谢!

I'm using Python and psycopg2 to interface to postgres.

When I insert a row...

sql_string = "INSERT INTO hundred (name,name_slug,status) VALUES ("
sql_string += hundred_name + ", '" + hundred_slug + "', " + status + ");"
cursor.execute(sql_string)

... how do I get the ID of the row I've just inserted? Trying:

hundred = cursor.fetchall() 

returns an error, while using RETURNING id:

sql_string = "INSERT INTO domes_hundred (name,name_slug,status) VALUES ("
sql_string += hundred_name + ", '" + hundred_slug + "', " + status + ") RETURNING id;"
hundred = cursor.execute(sql_string)

simply returns None.

UPDATE: So does currval (even though using this command directly into postgres works):

sql_string = "SELECT currval(pg_get_serial_sequence('hundred', 'id'));"
hundred_id = cursor.execute(sql_string)

Can anyone advise?

thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

无尽的现实 2024-10-28 15:12:00
cursor.execute("INSERT INTO .... RETURNING id")
id_of_new_row = cursor.fetchone()[0]

并且请不要手动构建包含值的 SQL 字符串。您可以(并且应该!)单独传递值,从而无需转义并且无法进行 SQL 注入:

sql_string = "INSERT INTO domes_hundred (name,name_slug,status) VALUES (%s,%s,%s) RETURNING id;"
cursor.execute(sql_string, (hundred_name, hundred_slug, status))
hundred = cursor.fetchone()[0]

请参阅 psycopg 文档以获取更多详细信息:http://initd.org/psycopg/docs/usage.html#passing-parameters-to-sql-queries

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

And please do not build SQL strings containing values manually. You can (and should!) pass values separately, making it unnecessary to escape and SQL injection impossible:

sql_string = "INSERT INTO domes_hundred (name,name_slug,status) VALUES (%s,%s,%s) RETURNING id;"
cursor.execute(sql_string, (hundred_name, hundred_slug, status))
hundred = cursor.fetchone()[0]

See the psycopg docs for more details: http://initd.org/psycopg/docs/usage.html#passing-parameters-to-sql-queries

倾`听者〃 2024-10-28 15:12:00

我最终来到这里是因为我遇到了类似的问题,但我们使用的是 Postgres-XC,它尚不支持 RETURNING ID 子句。在这种情况下,您可以使用:

cursor.execute('INSERT INTO ........')
cursor.execute('SELECT LASTVAL()')
lastid = cursor.fetchone()['lastval']

以防万一它对任何人都有用!

I ended up here because I had a similar problem, but we're using Postgres-XC, which doesn't yet support the RETURNING ID clause. In that case you can use:

cursor.execute('INSERT INTO ........')
cursor.execute('SELECT LASTVAL()')
lastid = cursor.fetchone()['lastval']

Just in case it was useful for anyone!

七禾 2024-10-28 15:12:00

对我来说,盗贼大师的答案和杰米·布朗的答案都不起作用。对我有用的是两者的结合,我想在这里回答,以便它可以帮助其他人。

我需要做的是:

cursor.execute('SELECT LASTVAL()')
id_of_new_row = cursor.fetchone()[0]

语句 lastid = curve.fetchone()['lastval'] 对我不起作用,即使在 cursor.execute('SELECT LASTVAL()' 之后)。单独的语句 id_of_new_row = curve.fetchone()[0] 也不起作用。

也许我错过了一些东西。

For me, neither ThiefMaster's answer worked nor Jamie Brown's. What worked for me was a mix of both, and I'd like to answer here so it can help someone else.

What I needed to do was:

cursor.execute('SELECT LASTVAL()')
id_of_new_row = cursor.fetchone()[0]

The statement lastid = cursor.fetchone()['lastval'] didn't work for me, even after cursor.execute('SELECT LASTVAL()'). The statement id_of_new_row = cursor.fetchone()[0] alone didn't work either.

Maybe I'm missing something.

因为看清所以看轻 2024-10-28 15:12:00

ThiefMaster 的方法对我来说很有效,适用于 INSERTUPDATE 命令。

如果在执行 INSERT/UPDATE 命令后在游标上调用 cursor.fetchone() 但缺少返回值 (RETURNING 子句)将引发异常:ProgrammingError('no results to fetch'))


insert_query = """
    INSERT INTO hundred (id, name, name_slug, status)
        VALUES (DEFAULT, %(name)s, %(name_slug)s, %(status)s)
        RETURNING id;
"""

insert_query_values = { 
    "name": "",
    "name_slug": "",
    "status": ""
}

connection = psycopg2.connect(host="", port="", dbname="", user="", password="")

try:
    with connection:
        with connection.cursor() as cursor:
            cursor.execute(insert_query, insert_query_values)
            num_of_rows_affected = cursor.rowcount
            new_row_id = cursor.fetchone()

except psycopg2.ProgrammingError as ex:
    print("...", ex)
    raise ex

finally:
    connection.commit()
    connection.close()


ThiefMaster's approach worked for me, for both INSERT and UPDATE commands.

If cursor.fetchone() is called on a cursor after having executed an INSERT/UPDATE command but lacked a return value (RETURNING clause) an exception will be raised: ProgrammingError('no results to fetch'))


insert_query = """
    INSERT INTO hundred (id, name, name_slug, status)
        VALUES (DEFAULT, %(name)s, %(name_slug)s, %(status)s)
        RETURNING id;
"""

insert_query_values = { 
    "name": "",
    "name_slug": "",
    "status": ""
}

connection = psycopg2.connect(host="", port="", dbname="", user="", password="")

try:
    with connection:
        with connection.cursor() as cursor:
            cursor.execute(insert_query, insert_query_values)
            num_of_rows_affected = cursor.rowcount
            new_row_id = cursor.fetchone()

except psycopg2.ProgrammingError as ex:
    print("...", ex)
    raise ex

finally:
    connection.commit()
    connection.close()


~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文