Home > Net >  How to rollback in psycopg2?
How to rollback in psycopg2?

Time:03-24

I´m forcing an error in qry2 so that a can run qry3 suposing it could rollback to save_1 but it doesn´t. Any catch? Using PostgreSql 14.2

qry1 = ('begin;'  
        'savepoint save_1;'  
        'delete from ntnb_cup;')

qry2 = ...
        # Force error

qry3 = 'rollback to save_1;'

try:
    cursor = conn.cursor()
    cursor.execute(qry1)
    conn.commit()
except Exception as err:
    cursor.close()
    conn.close()
    exit()

try:
    cursor.execute(qry2)
    conn.commit()  
except Exception as err:
    cursor.execute(qry3)
    conn.commit()    
finally:
    cursor.close()
    conn.close()

CodePudding user response:

try:
    cursor = conn.cursor()
    cursor.execute(qry1)
    conn.commit()

Once you commit, you are committed. To preserve the option of rolling back to a savepoint later, don't commit here.

  • Related