7

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?

Vikash Singh
  • 13,213
  • 8
  • 40
  • 70
Eugene
  • 588
  • 1
  • 8
  • 20
  • I believe the answers to [this question](http://stackoverflow.com/q/5408156/377366) are what you need. – KobeJohn Oct 10 '13 at 13:33
  • 2
    I was having a similar issue and what fixed my problem is adding the `session.close_all()` I saw in your question! That alongside `engine.dispose()` did the trick for me. – simlmx Jan 25 '16 at 17:39

1 Answers1

6

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.

Matthew Cox
  • 1,047
  • 10
  • 23
  • 1
    Technically, closing the sessions just checks the connections back into the pool. You need to call `engine.dispose()` to close the connections - [Engine Disposal](https://docs.sqlalchemy.org/en/20/core/connections.html#engine-disposal). – snakecharmerb Aug 11 '23 at 13:06