我有一个名为test_table
的表,其中有一个自动递增的字段id
。现在我想要在运行INSERT
语句后立即获取最后插入的id。但是目前我的所有尝试都导致返回None(顺便说一下,在MySQL中我也遇到了完全相同的问题,只有在SQLite中才一切正常)。以下是一些重现这种意外行为的代码:
>>> import psycopg2
>>> cnx = psycopg2.connect(host="127.0.0.1", dbname="reestr", user="postgres", password="postgres")
>>> cur = cnx.cursor()
>>> cur.execute("INSERT INTO test_table (field_1) VALUES ('hello')")
>>> cur.execute("INSERT INTO test_table (field_1) VALUES ('hello')")
>>> cur.execute("SELECT CURRVAL(pg_get_serial_sequence('test_table','id'))")
>>> res = cur.fetchone()
>>> res
(None,)
>>> cur.execute("SELECT id, field_1 FROM test_table")
>>> res = cur.fetchall()
>>> res
[(1, 'hello'), (2, 'hello')]
我们清楚地看到,id
列是自增的,但由于某种疯狂的原因,SELECT CURRVAL(pg_get_serial_sequence('test_table','id'))
没有返回任何结果。这是什么问题?顺便说一下,我还尝试在一个事务中显式运行这些查询,并得到了完全相同的结果。
max(id)
,或执行insert ... returning id
并收集最后一个值? - 9000max(id)
看起来有些不专业。我不想学习一些最大价格之类的东西,我只想学习自增列的最后插入值。 - JacobianSELECT CURRVAL(pg_get_serial_sequence ...
的存在意义。 - Jacobiantest_table
的创建表达式吗?谢谢。顺便说一句,这个链接也有关联:http://dba.stackexchange.com/questions/3281/how-do-i-use-currval-in-postgresql-to-get-the-last-inserted-id。 - alecxeCREATE TABLE test_table (id INTEGER NOT NULL DEFAULT nextval(auto_id_test_table), field_1 VARCHAR(128))
- Jacobian