gpt4 book ai didi

python-3.x - InternalError : current transaction is aborted, 命令在 UNIQUE 约束下被忽略,直到事务 block 结束

转载 作者:行者123 更新时间:2023-11-29 11:56:19 25 4
gpt4 key购买 nike

我试图用我的 except: 语句执行...同时尝试反对 UNIQUE 约束的功能..但以异常错误结束..Postgresql 数据库表已经包含我在

中使用的行

db.insert("The News","AparnaKumar",1995,234569654)

但它在插入不重复的行时效果很好..

import psycopg2
class database:

def __init__(self):

self.con=psycopg2.connect("dbname='book_store' user='postgres' password='5283' host='localhost' port='5432' ")
self.cur=self.con.cursor()
self.cur.execute("CREATE TABLE if not exists books(id SERIAL PRIMARY KEY,title TEXT NOT NULL UNIQUE,author TEXT NOT NULL,year integer NOT NULL,isbn integer NOT NULL UNIQUE)")
self.con.commit()

def insert(self,title,author,year,isbn):
try:
self.cur.execute("INSERT INTO books(title,author,year,isbn) VALUES(%s,%s,%s,%s)",(title,author,year,isbn))
self.con.commit()
except:
print("already exists..")

def view(self):
self.cur.execute("SELECT * FROM books")
rows=self.cur.fetchall()
print(rows)

def search(self,title=None,author=None,year=None,isbn=None):
self.cur.execute("SELECT * FROM books WHERE title=%s or author=%s or year=%s or isbn=%s",(title,author,year,isbn))
row=self.cur.fetchall()
print(row)

db=database()
db.insert("The News","AparnaKumar",1995,234569654)
db.view()
db.search(year=1995)

InternalError: current transaction is aborted, commands ignored until end of transaction block

最佳答案

您可以修改 python 函数以回滚事务,或者修改 sql 以在发生冲突时不插入新行(postgresql 版本 9.5+):

选项 1:

def insert(self,title,author,year,isbn):
try:
self.cur.execute("INSERT INTO books(title,author,year,isbn) VALUES(%s,%s,%s,%s)",(title,author,year,isbn))
self.con.commit()
except:
self.con.rollback()
print("already exists..")

选项 2(适用于 postgresql 9.5 或更高版本):

def insert(self,title,author,year,isbn):
try:
self.cur.execute("INSERT INTO books(title,author,year,isbn) VALUES(%s,%s,%s,%s) ON CONFLICT DO NOTHING",(title,author,year,isbn))
self.con.commit()
except:
print("already exists..")

关于python-3.x - InternalError : current transaction is aborted, 命令在 UNIQUE 约束下被忽略,直到事务 block 结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47707093/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com