Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With psycopg2 how to avoid using the connection context manager

With psycopg2, connection and querying the database works like so

conn = psycopg2.connect('connection string')
with conn:
    cur=conn.cursor()
    cur.execute("SELECT * FROM pg_stat_activity") #simple query 
    rows = cur.fetchall()
    for row in rows:
       print (row)

After trial and error, I found out that with conn is absolutely necessary or you will get many unexplained locks.

My question is: is there a way to setup the connection to avoid the need to use it?

like image 793
yigal Avatar asked Dec 13 '25 08:12

yigal


1 Answers

From https://www.psycopg.org/docs/usage.html,

Warning
Unlike file objects or other resources, exiting the connection’s with block doesn’t close the connection, but only the transaction associated to it. If you want to make sure the connection is closed after a certain point, you should still use a try-catch block:

   conn = psycopg2.connect(DSN)
   try:  
     # connection usage 
   finally:  
     conn.close()  
like image 162
Stephane B. Avatar answered Dec 16 '25 07:12

Stephane B.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!