Python / postgres / psycopg2:获取刚刚插入的行的ID [英] Python/postgres/psycopg2: getting ID of row just inserted

查看:405
本文介绍了Python / postgres / psycopg2:获取刚刚插入的行的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python和psycopg2连接到Postgres。

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)

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

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

hundred = cursor.fetchall() 

使用返回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)

简单返回

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

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)

有人可以建议吗?

谢谢!

推荐答案

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

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

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]

有关详细信息,请参见psycopg文档: http://initd.org/psycopg/docs/usage.html#passing-parameters-to-sql-queries

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

这篇关于Python / postgres / psycopg2:获取刚刚插入的行的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆