The libraries you need :
- pyodbc: for ODBC connections
- Azure Active Directory Authentication Library (adal) or msal: If you are using Azure Active Directory authentication
- pandas: to be able to work with data frames (optional, but useful)
To install these:
- Go to your Databricks workspace.
- Navigate to Clusters > Select your cluster.
- Click on Libraries > Install New.
- Install the following libraries:
- PyPI: Install
pyodbc
,pandas
,adal
, ormsal
.
- PyPI: Install
To connect to Azure Database for SQL Server, you need an ODBC driver. Databricks provides a built-in driver for this so depending on your authentication type:
- SQL Authentication:
driver = "{ODBC Driver 17 for SQL Server}"
server = "your-server.database.windows.net"
database = "your-database-name"
username = "your-username"
password = "your-password"
- Azure Active Directory Authentication :
conn_str = f"DRIVER={driver};SERVER={server};PORT=1433;DATABASE={database};UID={username};PWD={password};"
How to execute the stored SQL procedure :
import pyodbc
# Connection details
driver = "{ODBC Driver 17 for SQL Server}"
server = "your-server.database.windows.net"
database = "your-database-name"
username = "your-username"
password = "your-password"
# Connection string
conn_str = f"DRIVER={driver};SERVER={server};PORT=1433;DATABASE={database};UID={username};PWD={password};"
# Connect to the database
connection = pyodbc.connect(conn_str)
# Create a cursor
cursor = connection.cursor()
# Execute the stored procedure
stored_procedure = "EXEC YourStoredProcedureName @param1 = ?, @param2 = ?"
params = (value1, value2) # Replace with your actual parameter values
cursor.execute(stored_procedure, params)
# Commit the transaction (if required)
connection.commit()
# Fetch results (if the procedure returns any)
results = cursor.fetchall()
for row in results:
print(row)
# Close the connection
cursor.close()
connection.close()
Links to help you :
https://community.databricks.com/t5/data-engineering/sql-stored-procedure-in-databricks/td-p/26817
https://learn.microsoft.com/en-us/azure/databricks/connect/external-systems/sql-server
https://www.mssqltips.com/sqlservertip/6151/using-azure-databricks-to-query-azure-sql-database/