【问题标题】:Postgresql Python: ignore duplicate key exceptionPostgresql Python:忽略重复键异常
【发布时间】:2015-05-25 00:26:19
【问题描述】:

我通过以下方式使用 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()

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

【问题讨论】:

标签: python sql postgresql psycopg2


【解决方案1】:

来自Graceful Primary Key Error handling in Python/psycopg2

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

我在下面的代码中又添加了一个 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]

【讨论】:

    猜你喜欢
    • 2012-03-03
    • 1970-01-01
    • 2014-01-05
    • 1970-01-01
    • 1970-01-01
    • 2012-12-06
    • 1970-01-01
    • 2010-10-09
    相关资源
    最近更新 更多