Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sqlalchemy close all connection

I'm trying to drop my database using sqlalchemy:

def dropDb(self, dbName):
    self.closeConnection()
    self.selectDb(None)
    self.execute("drop database %s" % dbName)

def closeConnection(self):
    self._Session.close_all()
    self._engine.dispose()
    del self._Session
    del self._engine

I create the engine with:

sqlalchemy.create_engine(connection_string, poolclass = NullPool)

But I am getting the following error:

Detail ProgrammingError: (ProgrammingError) ('42000', '[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Cannot drop database "test_db" because it is currently in use. (3702) (SQLExecDirectW)') 'drop database test_db' ()

How can I forcibly close ALL connections?

like image 965
Eugene Avatar asked Aug 01 '13 11:08

Eugene


People also ask

How do I close a SQLAlchemy connection?

you call close(), as documented. dispose() is not needed and in fact calling dispose() explicitly is virtually never needed for normal SQLAlchemy usage.

Does SQLAlchemy close connection automatically?

close() method is automatically invoked at the end of the block. The Connection , is a proxy object for an actual DBAPI connection. The DBAPI connection is retrieved from the connection pool at the point at which Connection is created.

What is Create_engine in SQLAlchemy?

The create_engine() method of sqlalchemy library takes in the connection URL and returns a sqlalchemy engine that references both a Dialect and a Pool, which together interpret the DBAPI's module functions as well as the behavior of the database.

Is SQLAlchemy Engine thread safe?

Every pool implementation in SQLAlchemy is thread safe, including the default QueuePool . This means that 2 threads requesting a connection simultaneously will checkout 2 different connections. By extension, an engine will also be thread-safe.


1 Answers

The current method for closing all connections using the SQLAlchemy sessions api is

from sqlalchemy.orm import close_all_sessions

close_all_sessions()

as session.close_all() is deprecated.

like image 69
Matthew Cox Avatar answered Oct 01 '22 11:10

Matthew Cox