SQLAlchemy engine.execute() 使与数据库的连接处于休眠状态

SQLAlchemy engine.execute() leaves a connection to the database in sleeping status

我正在使用 SQL 服务器数据库。我注意到,在执行下面的代码时,我得到了一个到 'sleeping' 状态的数据库连接,状态为 'AWAITING COMMAND'。

    engine = create_engine(url, connect_args={'autocommit': True})
    res = engine.execute(f"CREATE DATABASE my_database")
    res.close()
    engine.dispose()

通过 engine.dispose() 调用后的断点,我可以在 EXEC sp_who2 table 中看到服务器上的一个条目。此条目仅在我终止进程后才消失。

可能Connection Pooling

Connection Pooling

A connection pool is a standard technique used to maintain long running connections in memory for efficient re-use, as well as to provide management for the total number of connections an application might use simultaneously.

Particularly for server-side web applications, a connection pool is the standard way to maintain a “pool” of active database connections in memory which are reused across requests.

SQLAlchemy includes several connection pool implementations which integrate with the Engine. They can also be used directly for applications that want to add pooling to an otherwise plain DBAPI approach.

.

I'm not sure if this is what gets in the way of my teardown method which drops the database

要删除可能正在使用的数据库,请尝试:

USE master;
ALTER DATABASE mydb SET RESTRiCTED_USER WITH ROLLBACK IMMEDIATE;
DROP DATABASE mydb;

你基本上想要终止所有连接你可以使用这样的东西:

对于 MS SQL Server 2012 及更高版本

USE [master];

DECLARE @kill varchar(8000) = '';  
SELECT @kill = @kill + 'kill ' + CONVERT(varchar(5), session_id) + ';'  
FROM sys.dm_exec_sessions
WHERE database_id  = db_id('MyDB')

EXEC(@kill);

对于 MS SQL 服务器 2000、2005、2008

USE master;

DECLARE @kill varchar(8000); SET @kill = '';  
SELECT @kill = @kill + 'kill ' + CONVERT(varchar(5), spid) + ';'  
FROM master..sysprocesses  
WHERE dbid = db_id('MyDB')

EXEC(@kill); 

或者更像脚本的东西:

DECLARE @pid SMALLINT, @sql NVARCHAR(100)
DECLARE curs CURSOR LOCAL FORWARD_ONLY FOR
  SELECT DISTINCT pid FROM master..sysprocesses where dbid = DB_ID(@dbname)
OPEN curs
fetch next from curs into @pid
while @@FETCH_STATUS = 0
BEGIN
    SET @sql = 'KILL ' + CONVERT(VARCHAR, @pid)
    EXEC(@sql)
    FETCH NEXT FROM curs into @pid
END
CLOSE curs
DEALLOCATE curs

可在此处找到更多内容: Script to kill all connections to a database (More than RESTRICTED_USER ROLLBACK)