InternalError:当前事务被中止,命令被忽略,直到事务块结束(受UNIQUE约束)

kir*_*ika 2 postgresql psycopg2 python-3.x

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

db.insert(“新闻”,“ 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)
Run Code Online (Sandbox Code Playgroud)

InternalError:当前事务中止,命令被忽略,直到事务块结束

Hal*_*Ali 5

您可以修改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..")
Run Code Online (Sandbox Code Playgroud)

选项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..")
Run Code Online (Sandbox Code Playgroud)