Graceful Primary Key Error handling in Python/psycopg2

后端 未结 2 730
没有蜡笔的小新
没有蜡笔的小新 2021-02-18 17:15

Using Python 2.7 and

In [150]: psycopg2.version Out[150]: \'2.4.2 (dt dec pq3 ext)\'

I have a simple python scripts that processing transaction

2条回答
  •  感动是毒
    2021-02-18 17:18

    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 encounter_id_table (
                encounter_id,current_date  )
                values       
                (%(create_date)s, %(encounter_id)s ) ;""",
                'encounter_id':i.split('~')[1],  
                'create_date': datetime.date.today() })
        except psycopg2.IntegrityError:
            conn.rollback()
        else:
            conn.commit()
    
        cur.close() 
    except Exception , e:
        print 'ERROR:', e[0]
    

提交回复
热议问题