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

Viewed 106
1 Answers

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.
Related