1

I tried to insert name into database.

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

error message:

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

When id=2301, it succeed,and return ID. After that,id += 1and returns the error below.

http://ob9j09f06.bkt.clouddn.com/2016-10-12-16%3A31%3A12.jpg

M1nt_zwy
  • 887
  • 3
  • 9
  • 19

2 Answers2

1

Seems to me that You already have record with ID 2321 in your DB. Can You check with SELECT id FROM scholars?

Fejs
  • 2,734
  • 3
  • 21
  • 40
0

Thanks @e4c5, @kxxoling

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 # normal

Community
  • 1
  • 1
M1nt_zwy
  • 887
  • 3
  • 9
  • 19