python - postgresql 插入时报错ID已存在
PHP中文网
PHP中文网 2017-04-18 09:44:40
[Python讨论组]

作插入操作:

name = 'test'
cur.execute("INSERT INTO scholars(name) VALUES('{}') returning id".format(name))
id = cur.fetchone()
print(id)

报错如下:

psycopg2.IntegrityError: duplicate key value violates unique constraint "idx_16514_primary"
DETAIL:  Key (id)=(2321) already exists.

id=2301时插入成功,并且成功返回ID。
之后插入一次,id+1,报错ID已存在。

数据库插入操作,ID不是自动寻找最大值,然后自增么?

PHP中文网
PHP中文网

认证高级PHP讲师

全部回复(1)
怪我咯

Here i got the answer How to reset postgres' primary key sequence when it falls out of sync? to this question.

Something was wrong with my id sequence.

I fixed it by doing this.

SELECT MAX(id) FROM scholars;

=> 11518

SELECT nextval('scholars_id_seq');

=> 2324 # here it is lower than max(id)

SELECT setval('scholars_id_seq', (SELECT MAX(id) FROM scholars));

=> 11518 # fix it

SELECT nextval('scholars_id_seq');

=> 11519 # done!

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号