Forum Discussion

yashaswi_raj's avatar
yashaswi_raj
Helper I
11 months ago
Solved

How to Connect to Azure SQL DB from Fabric Notebook

Can we connect to azure sql db from fabric notebook and insert data using stored procedures from fabric notebook itself
  • tayloramy's avatar
    11 months ago

    Hi yashaswi_raj

     

    Yes. You can connect from a Fabric notebook to Azure SQL DB and call stored procedures. The most reliable pattern is Python + pyodbc with a Microsoft Entra ID access token.

    1) Prereqs

    • Networking open to Fabric: either enable public connectivity (server firewall or "Allow Azure services...") or use Fabric Managed Private Endpoints (MPE). See Azure SQL network controls docs and Fabric MPE overview docs (how-to with notebook samples docs).
    • Permissions: your Entra user or service principal must exist in the database and have EXECUTE rights on the proc, e.g. CREATE USER [app-or-user] FROM EXTERNAL PROVIDER; GRANT EXECUTE ON SCHEMA::dbo TO [app-or-user]; (CREATE USER, GRANT on stored procedures).

    2) Notebook code 

    # In a Python cell
    %pip install pyodbc
    
    import struct, pyodbc
    from notebookutils import mssparkutils  # alias of mssparkutils in Fabric
    
    server   = "<yourserver>.database.windows.net"
    database = "<yourdb>"
    
    # Get Entra access token for Azure SQL
    token = mssparkutils.credentials.getToken("https://database.windows.net/")  # Fabric NotebookUtils <https://learn.microsoft.com/en-us/fabric/data-engineering/notebook-utilities>
    
    # Convert token for ODBC Driver 18 (SQL_COPT_SS_ACCESS_TOKEN = 1256)
    exptoken = b"".join(bytes([c]) + b"\x00" for c in token.encode("utf-8"))
    token_struct = struct.pack("=i", len(exptoken)) + exptoken
    
    conn_str = (
        "Driver={ODBC Driver 18 for SQL Server};"
        f"Server={server};Database={database};"
        "

     If you found this helpful, consider giving some Kudos. If I answered your question or solved your problem, please mark this as the solution.