【问题标题】:InternalError: current transaction is aborted, commands ignored until end of transaction block ,on UNIQUE constraintInternalError:当前事务被中止,命令被忽略直到事务块结束,在唯一约束上
【发布时间】:2017-12-08 03:05:13
【问题描述】:

我尝试使用我的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)

【问题讨论】:

    标签: python-3.x postgresql psycopg2


    【解决方案1】:

    您可以修改您的 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..")
    

    【讨论】:

      【解决方案2】:

      使用SAVEPOINT

      psycopg FAQ list中的第二个问题。

      【讨论】:

        【解决方案3】:

        如果您想保持事务打开,您应该在异常发生时使用 SAVEPOINT 和 ROLLBACK 到该 SAVEPOINT。但是由于您使用了一个包罗万象的异常(太宽泛),这也会发生在其他错误上。所以有点失控了。

        也许一个非常简单的解决方案是使用 SELECT 检查您要插入的记录是否已经存在。

        【讨论】:

          猜你喜欢
          • 2011-01-13
          • 1970-01-01
          • 2011-04-05
          • 2013-08-04
          • 2012-05-11
          • 2016-12-11
          • 1970-01-01
          • 2011-12-06
          • 2013-10-25
          相关资源
          最近更新 更多