Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python SQLAlchemy Basics Introduction to SQLAlchemy What is SQLAlchemy?

Srujana Puppala
Srujana Puppala
3,240 Points

SqlAlchemy open a connection as idle in postgresql database

in SqlAlchemy when i connect to postgresql database it open a connection in pool and even if i close the connection it remains idle there. for that my connection pool getting full and throwing error.

Any solution for that.

1 Answer

Hey there Srujana Puppala! I am not personally familiar with connecting a Postgresql database with a sqlalchemy database so I am not too sure what is going on there, but I googled your issue and this is what is coming up.

Sorry I can't be more helpful with this but if you can provide more details with what you are trying to do I would be happy to try and help you find a solution.

Srujana Puppala
Srujana Puppala
3,240 Points

Thanks Rumsey for your respose. So now i am going to share my code, what i have done and what is problem i am facing.

DB_URL = 'postgresql+psycopg2://{user}:{pw}@{url}/{db}'.format(
            user=POSTGRES_USER,pw=POSTGRES_PW,url=POSTGRES_URL,db=POSTGRES_DB )

app.config['SQLALCHEMY_DATABASE_URI'] = DB_URL
# silence the deprecation warning
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False 

# initialize the database connection '''
db = SQLAlchemy(app)
#db = SQLAlchemy()

engine_container = db.get_engine(app)

Then i import it

from dbconfig import db, engine_container

then when ever i want to execute query, i write like this

result = db.session.execute(""" Select district_name, district_code From table name """)
then i close the connection

  #explicitly close the session and  also closes the connection '''
   db.session.close()
   db.session.remove()
   engine_container.dispose()

But my problem is the connection remain open and when my user no increase the postgresql connection pool getting full and show an error these connection are for reserve. i search it for online and find out it is happening due to no more connection left as connection pool is full. i also check it on pgadmin and find out all connection are in idle positiion.

connection are not terminated even if db.session.close() commamd

can you help me what to do.