简体   繁体   中英

SQLAlchemy / pyODBC not releasing database connection

I'm using SQLAlchemy (Core only, not ORM) to create a connection to a 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 ).

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.

I'm using as hostname based connection as specified here .

Versions:

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

Edit : I've rewritten my code to solely use pyODBC instead of SQLAlchemy + pyODBC, and the issue remains. So as far as I can see, the issue is caused by pyODBC keeping the connection open.

When only pyODBC, the issue is because of connection pooling as discussed here .

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. The default is True, which enables ODBC connection pooling.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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