使用 psycopg2 返回一个值
理想情况下,我希望能够执行以下操作:
id_of_new_row = cursor.lastrowid()
其中我获取新创建或修改的行的 id。但这不能通过 psycopg2 获得。或者,我尝试过这个:
id_of_new_row = cursor.execute('INSERT INTO this_table (value1, value2, value3) VALUES (%s, %s, %s) RETURNING id', (some_value1, some_value2, some_value3))
这不起作用,可能是因为在提交之前它不会知道 id...
帮助!
Ideally I'd like to be able to do something like:
id_of_new_row = cursor.lastrowid()
in which I get the id of the newly created or modified row. But this isn't available through psycopg2. Alternatively, I've tried this:
id_of_new_row = cursor.execute('INSERT INTO this_table (value1, value2, value3) VALUES (%s, %s, %s) RETURNING id', (some_value1, some_value2, some_value3))
which doesn't work, probably because it won't know the id until after the commit is made...
Help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当然可以,命令完成后它就会知道 ID,这就是 RETURNING 的实现方式。不过,您需要实际获取它,因此类似:
应该在您的场景中工作。
Sure it will, it'll know the ID as soon as the command finishes, that's how RETURNING is implemented. You need to actually fetch it though, so something like:
should work in your scenario.
RETURNING 适用于 Postgresql >= 8.2
RETURNING works on Postgresql >= 8.2