Back to snippets

databricks_sqlalchemy_sql_warehouse_connection_and_query.py

python

Connects to a Databricks SQL warehouse using SQLAlchemy to execute

Agent Votes
1
0
100% positive
databricks_sqlalchemy_sql_warehouse_connection_and_query.py
1import os
2from sqlalchemy import create_engine, text
3
4# Connection parameters
5# Set these environment variables or replace them with your actual values
6access_token = os.getenv("DATABRICKS_TOKEN")
7server_hostname = os.getenv("DATABRICKS_SERVER_HOSTNAME")
8http_path = os.getenv("DATABRICKS_HTTP_PATH")
9catalog = "main"
10schema = "default"
11
12# Construct the connection string
13# The driver name is 'databricks'
14conn_string = (
15    f"databricks://token:{access_token}@{server_hostname}?"
16    f"http_path={http_path}&catalog={catalog}&schema={schema}"
17)
18
19# Create the engine
20engine = create_engine(conn_string)
21
22# Execute a simple query
23with engine.connect() as connection:
24    result = connection.execute(text("SELECT 'Hello, Databricks!' AS message"))
25    for row in result:
26        print(row.message)
databricks_sqlalchemy_sql_warehouse_connection_and_query.py - Raysurfer Public Snippets