Postgresql Python:忽略重复键异常

前端之家收集整理的这篇文章主要介绍了Postgresql Python:忽略重复键异常前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我按以下方式使用psycopg2插入项目:

  1. cursor = connection.cursor()
  2. for item in items:
  3. try:
  4. cursor.execute(
  5. "INSERT INTO items (name,description) VALUES (%s,%s) RETURNING id",(item[0],item[1])
  6. )
  7. id = cursor.fetchone[0]
  8. if id is not None:
  9. cursor.execute(
  10. "INSERT INTO item_tags (item,tag) VALUES (%s,(id,'some_tag')
  11. )
  12. except psycopg2.Error:
  13. connection.rollback()
  14. print("Postgresql Error: " + e.diag.message_primary)
  15. continue
  16. print(item[0])
  17. 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.

  1. try:
  2. cur = conn.cursor()
  3.  
  4. try:
  5. cur.execute( """INSERT INTO items (name,description)
  6. VALUES (%s,%s) RETURNING id""",item[1]))
  7. except psycopg2.IntegrityError:
  8. conn.rollback()
  9. else:
  10. conn.commit()
  11.  
  12. cur.close()
  13. except Exception,e:
  14. print 'ERROR:',e[0]

猜你在找的Postgre SQL相关文章