如何修复postgresql重复键违反唯一约束?
在将数据库从Microsoft SQL迁移到Postgresql后不久,我试图添加新记录只是为了解决问题: Original exception was: (psycopg2.errors.UniqueViolation) duplicate key value violates unique constraint "some_table_pkey" DETAIL: Key (id)=(2) al
·
在将数据库从Microsoft SQL
迁移到Postgresql
后不久,我试图添加新记录只是为了解决问题:
Original exception was:
(psycopg2.errors.UniqueViolation) duplicate key value
violates unique constraint "some_table_pkey"
DETAIL: Key (id)=(2) already exists.
进入全屏模式 退出全屏模式
似乎这是容易发生每当对数据库进行批量更新时,如何修复它?
那么为什么只有在进行批量更新时才会发生这种情况呢?
在进行批量更新时,主键序列不会增加,因为主键已经存在于记录中。
# Imports first!
import pandas as pd
from sqlalchemy import create_engine
# Postgres instance can only be accessed with sslmode
ssl_args = {
"sslcert": r"C:\.postgresql\postgresql.crt",
"sslkey": r"C:\.postgresql\postgresql.key",
"sslmode": "require",
}
# create a sqlalchemy engine
sqlengine = create_engine(
"postgresql+psycopg2://admin:password@x.x.x.x:5432/thedatabase",
connect_args=ssl_args,
)
# Repeat the following steps for the all tables with primary key
table = "problem_table"
pkey = "pkey"
# Get the serial sequence reference using pg_get_serial_sequence
output = pd.read_sql(f"SELECT pg_get_serial_sequence('{table}', '{pkey}');", con=sqlengine )
# Set the serial sequence value to the max value of the primary key
output = pd.read_sql(f"SELECT setval('{output.iloc[0][0]}', (SELECT MAX({pkey}) FROM {table})+1);", con=sqlengine )
进入全屏模式 退出全屏模式
更多推荐
已为社区贡献19912条内容
所有评论(0)