简体   繁体   中英

Using context manager with psycopg2

I have an update statement as below:

  with conn.cursor() as cursor:
        LOGGER.info('Batch updating for issues which neeeds to be closed......')
        create_temp_table(conn, 'temp_closed_issues')
        copy_from_stringio(conn, close_df, table='temp_closed_issues')
        query = """
            WITH update_cte as (
            SELECT issue_id, device_id, 
            daterange(start_date, end_date) as new_issue_date
            FROM temp_closed_issues
            )
            UPDATE {table} 
            SET issue_date = update_cte.new_issue_date
            FROM update_cte
            WHERE update_cte.issue_id = {table}.issue_id
            AND update_cte.device_id = {table}.device_id
            AND lower(update_cte.new_issue_date) = lower({table}.issue_date)         
            """.format(table=table)
        cursor.execute(query)
        LOGGER.info("updated records: %s", cursor.rowcount)

I am trying to understand the behaviour of using cursor as context manager. I do understand that in above block when the WITH block exits cursor is closed. If an exception is raised does this roll back the transaction automatically or we need to raise the exception. Moreover the records are commited to the database without explicitly using cursor.commit()

The records are committed or rolled back automatically, only when you are using the context manager for the connection, because commit()/rollback() are methods of the connection.

SQL = "INSERT INTO ..."
# The context manager commits when no exception was raised, else wise roll back!
with psycopg2.connect(DSN) as conn:
    with conn.cursor() as curs:
        curs.execute(SQL, ('val_1', 'val_2', ...))

Context-less connection:

conn = psycopg2.connect(DSN)
with conn.cursor() as curs:
    curs.execute(SQL, ('val_1', 'val_2', ...))
    # You need to commit/roll back manually 
    # conn.commit()

Have a look at the docs for further information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM