[Python] Azure SQL Database Connection Timeout from Azure Function (Python)

Discussão em 'Python' iniciado por Stack, Março 3, 2025.

  1. Stack

    Stack Membro Participativo

    I have an Azure Function (Python runtime, consumption plan) that needs to connect to an Azure SQL Database. I'm using the pyodbc library to connect. Most of the time, it works fine, but intermittently, I'm getting connection timeout errors. The error looks something like this:

    pyodbc.OperationalError: ('HYT00', '[HYT00] [Microsoft][ODBC Driver 18 for SQL Server]Login timeout expired (0) (SQLDriverConnect)')


    I've tried increasing the timeout parameter in the pyodbc.connect() call, but it doesn't seem to resolve the intermittent timeouts. It seems to happen more often under heavier load.

    What could be causing these intermittent connection timeouts, and how can I make my Azure Function's connection to the Azure SQL Database more reliable?

    My Code:

    import pyodbc
    import os
    import logging

    def main(req: func.HttpRequest) -> func.HttpResponse:
    try:
    server = os.environ["SQL_SERVER"]
    database = os.environ["SQL_DATABASE"]
    connection_string = f"Driver={{ODBC Driver 18 for SQL Server}};Server=tcp:{server},1433;Database={database};Authentication=ActiveDirectoryMsi;"

    # Attempt to connect (with a longer timeout, which doesn't fix the issue)
    with pyodbc.connect(connection_string, timeout=60) as conn:
    with conn.cursor() as cursor:
    cursor.execute("SELECT @@VERSION")
    row = cursor.fetchone()
    logging.info(f"SQL Version: {row[0]}")

    return func.HttpResponse("Successfully connected to the database.", status_code=200)

    except Exception as e:
    logging. Error(f"Error connecting to database: {e}")
    return func.HttpResponse("Failed to connect to the database.", status_code=500)

    Continue reading...

Compartilhe esta Página