Goal
A Python service, such as an API, an Azure Function, a report generator or a reconciliation script, needs to run SQL against an Azure Databricks SQL warehouse. It must not use a personal access token, must be safe from SQL injection, and must not fall over on large results or a warehouse that is stopped.
databricks-sql-connector is the DB-API 2.0 driver for Databricks SQL warehouses. It does not support jobs compute. For one-off shell scripts without Python, see the Statement Execution API post instead.
Step 1: install the right package
pip install "databricks-sql-connector[pyarrow]" databricks-sdk
- From version 4.0.0, PyArrow is optional and not installed by default. Without it, Cloud Fetch and the Arrow fetch methods aren't available, so large results are slower or fail. Install the
[pyarrow]extra for anything that reads more than a few thousand rows. - The SQLAlchemy dialect moved to a separate package in 4.x. If you upgrade from 3.x and
create_engine("databricks://...")breaks, that's why. - Pin exact versions in
requirements.txt. Releases have been yanked before. Check the release notes before you upgrade.
Step 2: get the hostname and HTTP path
In the warehouse's Connection details tab, copy the Server hostname and HTTP path. Or use the CLI:
databricks warehouses get 1234567890abcdef --output json \
| jq '{hostname: .odbc_params.hostname, http_path: .odbc_params.path}'
Store them as configuration (DATABRICKS_SERVER_HOSTNAME, DATABRICKS_HTTP_PATH), not in code.
Step 3: give the app an identity
Create a Microsoft Entra ID or Databricks-managed service principal for the app. Then:
- Add it to the workspace.
- Grant it Can use on the SQL warehouse (warehouse Permissions dialog).
- Grant the Unity Catalog privileges it needs, and nothing more:
GRANT USE CATALOG ON CATALOG main TO `app-orders-api`;
GRANT USE SCHEMA ON SCHEMA main.reporting TO `app-orders-api`;
GRANT SELECT ON TABLE main.reporting.v_orders TO `app-orders-api`;
Use the service principal's application ID (or its display name, depending on how it was added) as the principal name. Check how it appears in SHOW GRANTS.
Step 4: connect with OAuth M2M
For a Databricks OAuth secret on the service principal (connector 2.7.0+, databricks-sdk 0.18.0+):
import os
from databricks import sql
from databricks.sdk.core import Config, oauth_service_principal
HOST = os.environ["DATABRICKS_SERVER_HOSTNAME"]
HTTP_PATH = os.environ["DATABRICKS_HTTP_PATH"]
def credential_provider():
config = Config(
host=f"https://{HOST}",
client_id=os.environ["DATABRICKS_CLIENT_ID"],
client_secret=os.environ["DATABRICKS_CLIENT_SECRET"],
)
return oauth_service_principal(config)
def get_connection():
return sql.connect(
server_hostname=HOST,
http_path=HTTP_PATH,
credentials_provider=credential_provider,
catalog="main",
schema="reporting",
user_agent_entry="orders-api",
)
Keep the client secret in Key Vault or app settings that reference Key Vault. The SDK refreshes the OAuth token for you.
Managed identity instead of a secret
If the app runs on Azure (App Service, Functions, AKS with workload identity, a VM), get an Entra ID token for the Azure Databricks resource and pass it as access_token:
from azure.identity import DefaultAzureCredential
# Well-known application ID of the Azure Databricks resource
DATABRICKS_SCOPE = "2ff814a6-3304-4ab8-85cb-cd0e6f879c1d/.default"
def get_connection():
token = DefaultAzureCredential().get_token(DATABRICKS_SCOPE).token
return sql.connect(
server_hostname=HOST,
http_path=HTTP_PATH,
access_token=token,
user_agent_entry="orders-api",
)
The managed identity must be added to the workspace as a service principal and granted as in Step 3.
Warning
Entra ID tokens last about an hour by default. A static
access_tokenisn't refreshed. Open a new connection per request or batch, or reconnect when you see an expired-token error. Don't hold one connection open for days.
Step 5: run queries with native parameters
Connector 3.0.0 and above sends parameters to the server separately from the SQL text. Use them. Never build SQL with f-strings.
with get_connection() as conn, conn.cursor() as cur:
# Positional
cur.execute(
"SELECT order_id, amount FROM v_orders WHERE region = ? AND order_date >= ? LIMIT ?",
["EMEA", "2026-11-01", 100],
)
rows = cur.fetchall()
# Named
cur.execute(
"SELECT count(*) AS n FROM v_orders WHERE region = :region",
{"region": "EMEA"},
)
print(cur.fetchone().n)
Parameters cover values only. For a table or column name that varies, check it against an allowlist in code and use IDENTIFIER(:tbl) in the SQL.
Put a ceiling on runtime
cur.execute("SET STATEMENT_TIMEOUT = 600") # seconds, this session only
Call cur.cancel() from another thread to stop a running statement, then close the cursor. Closing cursors and connections releases server-side resources. The with blocks above do this for you.
Step 6: read large results without running out of memory
fetchall() loads everything into Python objects. For large results, stream Arrow batches:
with get_connection() as conn, conn.cursor() as cur:
cur.execute("SELECT * FROM main.reporting.orders_daily WHERE order_date >= ?", ["2026-01-01"])
while True:
batch = cur.fetchmany_arrow(100_000) # pyarrow.Table
if batch.num_rows == 0:
break
write_batch(batch.to_pandas())
With PyArrow installed, large results use Cloud Fetch. The client downloads result files straight from the workspace's storage account, not through the control plane. If that storage is behind a firewall your app can't reach, small queries work but large ones hang or fail. Either open the path or set use_cloud_fetch=False on connect(). That's slower but stays on the control plane.
Tip
If you're exporting millions of rows to a file, don't pull them through Python at all. Have the warehouse write to a Unity Catalog volume or table, and give consumers access to that.
Errors and what they mean
| Symptom or message | Cause | Fix |
|---|---|---|
tokenAuthWrapperInvalidAccessToken / 401 | Token expired, wrong tenant, or SP not in workspace | Refresh token per connection; add SP to the workspace |
IpAclValidation / 403 on connect | Workspace IP access list blocks the app's egress IP | Add the app's outbound IP or NAT IP to the allow list |
gaierror / name resolution failure | Wrong hostname or Private Link DNS not resolving from the app's network | Use the hostname from Step 2; fix the private DNS zone link |
| 403 / permission error on the warehouse | SP lacks Can use on the warehouse | Grant it on the warehouse |
INSUFFICIENT_PERMISSIONS on a table | Missing Unity Catalog grant | Grant USE CATALOG, USE SCHEMA, SELECT |
TABLE_OR_VIEW_NOT_FOUND with a two-part name | Default catalog isn't the one you expect (often hive_metastore) | Pass catalog= on connect or use three-part names |
| First query takes minutes | Warehouse was stopped and is starting | Expected after auto stop. Use serverless, or warm it before batch windows |
Hangs on fetchall() for big results only | Cloud Fetch blocked by storage firewall | Open the storage path or use_cloud_fetch=False |
ImportError for pyarrow or Arrow methods missing | 4.x installed without the extra | pip install "databricks-sql-connector[pyarrow]" |
A safe retry wrapper
Retry connection-level failures for read-only queries. Don't retry writes blindly. A timeout doesn't mean the statement didn't run.
import time
from databricks.sql.exc import RequestError
def run_read(query, params=None, attempts=3):
for i in range(attempts):
try:
with get_connection() as conn, conn.cursor() as cur:
cur.execute(query, params)
return cur.fetchall()
except RequestError:
if i == attempts - 1:
raise
time.sleep(2 ** i * 5)
Exception class names can differ between connector versions. Check databricks.sql.exc in your pinned version.
Find your app's queries
user_agent_entry labels traffic from your app. In Query History, filter by the service principal. Or use system tables:
SELECT start_time, executed_by, execution_status, total_duration_ms, statement_text
FROM system.query.history
WHERE executed_by = 'app-orders-api' -- or the SP's application ID
AND start_time >= current_timestamp() - INTERVAL 1 DAY
ORDER BY total_duration_ms DESC
LIMIT 50;
Column names vary as system tables evolve. Run DESCRIBE system.query.history on your workspace first.
Prevent it next time
- One service principal per app, with Can use on one warehouse and minimal Unity Catalog grants.
- No personal access tokens in app config. Use OAuth M2M or managed identity, and refresh tokens per connection.
- Pin the connector version, install the
[pyarrow]extra, and test upgrades against a non-production warehouse. - Always use native parameters,
SET STATEMENT_TIMEOUTandwithblocks. - Check that the app's network reaches the workspace hostname, and the storage account for Cloud Fetch, before go-live, not after the first large query.
Get the weekly HubDatAI email
One email a week with everything new: posts, learning sessions and videos. Free, no spam, unsubscribe in one click. What you get