简体   繁体   English

SQLAlchemy / pyODBC不释放数据库连接

[英]SQLAlchemy / pyODBC not releasing database connection

I'm using SQLAlchemy (Core only, not ORM) to create a connection to a SQL Server 2008 SP3. 我正在使用SQLAlchemy(仅​​核心,不是ORM)创建与SQL Server 2008 SP3的连接。

When looking at the process' network connections, I noticed that the TCP/IP connection to the SQL Server (port 1433) remains open ( ESTABLISHED ). 在查看进程的网络连接时,我注意到与SQL Server的TCP / IP连接(端口1433)保持打开状态( ESTABLISHED )。

Sample code: 样例代码:

from urllib.parse import quote_plus
from sqlalchemy.pool import NullPool
import sqlalchemy as sa

# parameters are read from a config file
db_params = quote_plus(';'.join(['{}={}'.format(key, val) for key, val in db_config.items()]))
# Hostname based connection
engine = sa.create_engine('mssql:///?odbc_connect={}'.format(db_params), 
                          poolclass=NullPool)

conn = engine.connect()
conn.close()

engine.dispose()
engine = None

I added the NullPool and the engine.dispose() afterwards, thinking they might solve the lingering connection, but alas. 之后,我添加了NullPoolengine.dispose() ,以为它们可以解决缠绵的连接,但是可惜。

I'm using as hostname based connection as specified here . 我使用的是此处指定的基于主机名的连接。

Versions: 版本:

  • Python 3.5.0 (x32 on Win7) Python 3.5.0(在Win7上为x32)
  • SQLAlchemy 1.0.10 SQLAlchemy 1.0.10
  • pyODBC 3.0.10 pyODBC 3.0.10

Edit : I've rewritten my code to solely use pyODBC instead of SQLAlchemy + pyODBC, and the issue remains. 编辑 :我已经重写代码以仅使用pyODBC代替SQLAlchemy + pyODBC,问题仍然存在。 So as far as I can see, the issue is caused by pyODBC keeping the connection open. 据我所知,问题是由pyODBC保持连接打开引起的。

When only pyODBC, the issue is because of connection pooling as discussed here . 仅当使用pyODBC时, 问题是由于此处讨论的连接池引起的。

As described in the docs : 文档中所述:

pooling 汇集

A Boolean indicating whether connection pooling is enabled. 一个布尔值,指示是否启用连接池。 This is a global (HENV) setting, so it can only be modified before the first connection is made. 这是全局(HENV)设置,因此只能在建立第一个连接之前进行修改。 The default is True, which enables ODBC connection pooling. 默认值为True,这将启用ODBC连接池。

Thus: 从而:

import pyodbc

pyodbc.pooling = False 
conn = pyodbc.connect(db_connection_string) 
conn.close()

It seems that when using SQLAlchemy and disabling the SA pooling by using the NullPool , this isn't passed down to pyODBC. 似乎在使用SQLAlchemy并通过使用NullPool禁用SA池时,这并没有传递给pyODBC。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM