加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Postgresql Python:忽略重复键异常

发布时间:2020-12-13 15:49:33 所属栏目:百科 来源:网络整理
导读:我按以下方式使用psycopg2插入项目: cursor = connection.cursor()for item in items: try: cursor.execute( "INSERT INTO items (name,description) VALUES (%s,%s) RETURNING id",(item[0],item[1]) ) id = cursor.fetchone[0] if id is not None: cursor
我按以下方式使用psycopg2插入项目:

cursor = connection.cursor()
for item in items:
    try:
        cursor.execute(
            "INSERT INTO items (name,description) VALUES (%s,%s)  RETURNING id",(item[0],item[1])
        )
        id = cursor.fetchone[0]
        if id is not None:
            cursor.execute(
                "INSERT INTO item_tags (item,tag) VALUES (%s,(id,'some_tag')
            )    
    except psycopg2.Error:
        connection.rollback()
        print("PostgreSQL Error: " + e.diag.message_primary)
        continue
    print(item[0])
connection.commit()

显然,当一个项目已经在数据库中时,将抛出重复的键异常.有没有办法忽略这个例外?抛出异常时是否会中止整个事务?如果是,那么重写查询的最佳选择是什么,可能使用批量插入?

解决方法

从 Graceful Primary Key Error handling in Python/psycopg2:

You should rollback transaction on error.

I’ve added one more try..except..else construction in the code bellow
to show the exact place where exception will occur.

try:
    cur = conn.cursor()

    try:
        cur.execute( """INSERT INTO items (name,description) 
                      VALUES (%s,%s)  RETURNING id""",item[1]))
    except psycopg2.IntegrityError:
        conn.rollback()
    else:
        conn.commit()

    cur.close() 
except Exception,e:
    print 'ERROR:',e[0]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读