2

I am running some code on jupyter notebook, there are some SQL queries to an aws redshift database.

The problem is after executing these queries even when I am not running anything on the notebook looks like the tables stay read-locked.

When I close the terminal running the notebook the lock releases.

Sample of running code

def met():
    con=psycopg2.connect(host=
                         ,user=
                         ,password=
                         ,port=
                         ,dbname =)
    table_data = pd.read_sql_query(query, con)
    con.close()
tanaka
  • 401
  • 1
  • 4
  • 13

1 Answers1

0

Your cursor might be staying open, you should wrap it in a try-except-finally in order to ensure it closes when you are done with your query:

cursor = None
try:
    cursor = db.cursor()
    cursor.execute("""SELECT foo FROM bar""")
    module.rase_unexpected_error()
    cursor.commit()
except BaseException:
    if cursor is not None:
        cursor.rollback()
finally:
    if cursor is not None:
        cursor.close()

check out this question for more info: use try/except with psycopg2 or "with closing"?

foobarbaz
  • 508
  • 1
  • 10
  • 27
  • Is the "con.close()" command not enough to close the connection ? – tanaka Feb 15 '19 at 13:28
  • It closes the connection, not the cursor, and would not be guaranteed to run if your code errors out before reaching it. It is also good style to either close both, or use "with" as described in the link in the answer. See also https://stackoverflow.com/a/39616258/7692562 – foobarbaz Feb 15 '19 at 15:37