markfickett
markfickett

Reputation: 773

How do you set a query timeout for MS SQL using SqlAlchemy with pymssql?

The pymssql.connect documentation lists a timeout argument, but how do you pipe that through from SqlAlchemy using a mssql+pymssql:// connection?

Upvotes: 2

Views: 2255

Answers (1)

markfickett
markfickett

Reputation: 773

Through experimentation, it must be passed as a connection URL query parameter:

from sqlalchemy import create_engine

ms_url = f"mssql+pymssql://{username}:{password}@{host}:{port}?timeout=10"
ms_engine = create_engine(
  ms_url,
  pool_pre_ping=True,  # any other args
  connect_args={
    # other connect args for example; but timeout does not work here
    "login_timeout": 3,
  },
)
connection = ms_engine.connect()

Alternatives did not work:

  • Passing connect_args={"timeout": 10} does not work, queries longer than 10s still run.
  • The sqlalchemy.engine.Engine.connect() call does not accept a timeout kwarg.

Upvotes: 2

Related Questions