Database connection with postgres keeps on disconnecting in the server in python language

727 Views Asked by At
import psycopg2
from psycopg2 import pool
connection_pool = psycopg2.pool.ThreadedConnectionPool(1, 50, user='A', password='S', host='D',port='D', database='AD')

def fetch_data(id):
    try:
        sql = build_sql_query('SELECT * FROM USERS')
        connection = connection_pool.getconn()
        cursor = connection.cursor()
        cursor.execute(sql)
        records = cursor.fetchall()
    except (Exception, psycopg2.Error) as error :
        print ("Error while connecting to PostgreSQL", error)

I dont want to disconnect the connection . Want to make the global connection with postgres with lifetime. I have tried alot but if there is anyway, let me know.

1

There are 1 best solutions below

0
On

In my hands it doesn't disconnect each time. They just accumulate.

You have to do:

connection_pool.putconn(connection)

when you are done with a connection. Maybe you think that should happen automatically when it goes out of scope, but apparently it does not.