Databricks SQL Connector for Python

4.2.5 · active · verified Sat Mar 28

The Databricks SQL Connector for Python is a Python library that enables running SQL commands on Databricks clusters and SQL warehouses. It is a Thrift-based client, conforms to the Python DB API 2.0 specification, and uses Apache Arrow for efficient data exchange. The library is actively maintained with frequent releases, often multiple times a month.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to establish a connection to a Databricks SQL warehouse using a Personal Access Token (PAT) and execute a simple query. Ensure that `DATABRICKS_SERVER_HOSTNAME`, `DATABRICKS_HTTP_PATH`, and `DATABRICKS_TOKEN` environment variables are set with your Databricks connection details.

import os
from databricks import sql

# Ensure these environment variables are set:
# DATABRICKS_SERVER_HOSTNAME, DATABRICKS_HTTP_PATH, DATABRICKS_TOKEN

host = os.environ.get('DATABRICKS_SERVER_HOSTNAME', 'your_server_hostname.databricks.com')
http_path = os.environ.get('DATABRICKS_HTTP_PATH', '/sql/1.0/endpoints/your_sql_warehouse_id')
access_token = os.environ.get('DATABRICKS_TOKEN', 'dapiXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')

if not all([host, http_path, access_token]):
    print("Please set DATABRICKS_SERVER_HOSTNAME, DATABRICKS_HTTP_PATH, and DATABRICKS_TOKEN environment variables.")
else:
    try:
        with sql.connect(
            server_hostname=host,
            http_path=http_path,
            access_token=access_token
        ) as connection:
            with connection.cursor() as cursor:
                cursor.execute("SELECT 1 as id, 'hello' as message")
                result = cursor.fetchall()
                for row in result:
                    print(row)
    except Exception as e:
        print(f"An error occurred: {e}")

view raw JSON →