This is a sample code I'd like to run:
for i in range(1,2000):
db = create_engine('mysql://root@localhost/test_database')
conn = db.connect()
#some simple data operations
conn.close()
db.dispose()
Is there a way of running this without getting "Too many connections" errors from MySQL? I already know I can handle the connection otherwise or have a connection pool. I'd just like to understand how to properly close a connection from sqlalchemy.
4条答案
按热度按时间t40tm48m1#
Here's how to write that code correctly:
That is, the
Engine
is a factory for connections as well as a pool of connections, not the connection itself. When you sayconn.close()
, the connection is returned to the connection pool within the Engine, not actually closed.If you do want the connection to be actually closed, that is, not pooled, disable pooling via
NullPool
:With the above
Engine
configuration, each call toconn.close()
will close the underlying DBAPI connection.If OTOH you actually want to connect to different databases on each call, that is, your hardcoded
"localhost/test_database"
is just an example and you actually have lots of different databases, then the approach usingdispose()
is fine; it will close out every connection that is not checked out from the pool.In all of the above cases, the important thing is that the
Connection
object is closed viaclose()
. If you're using any kind of "connectionless" execution, that isengine.execute()
orstatement.execute()
, theResultProxy
object returned from that execute call should be fully read, or otherwise explicitly closed viaclose()
. AConnection
orResultProxy
that's still open will prohibit theNullPool
ordispose()
approaches from closing every last connection.qlzsbp2j2#
Tried to figure out a solution to disconnect from database for an unrelated problem (must disconnect before forking).
You need to invalidate the connection from the connection Pool too.
In your example:
58wvjzkj3#
I use this one
wsewodh24#
In my case these always works and I am able to close! So using invalidate() before close() makes the trick. Otherwise close() sucks.