Postgresql Python:忽略重复键异常

nic*_*ted 4 python sql postgresql psycopg2

我按以下方式使用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, %s)  RETURNING id",
                (id, 'some_tag')
            )    
    except psycopg2.Error:
        connection.rollback()
        print("PostgreSQL Error: " + e.diag.message_primary)
        continue
    print(item[0])
connection.commit()
Run Code Online (Sandbox Code Playgroud)

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

小智 13

来自Python/psycopg2中的Graceful Primary Key错误处理:

您应该在出错时回滚事务.

我在下面的代码中添加了一个try..except..else构造,以显示异常将发生的确切位置.

try:
    cur = conn.cursor()

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

    cur.close() 
except Exception , e:
    print 'ERROR:', e[0]
Run Code Online (Sandbox Code Playgroud)