The local embedded mode runs a full Databend engine in-process without any
server. It is useful for local analytics, testing, and offline workflows.
Install the local extra to pull in the embedded engine:
pip install "databend-driver[local]"
The embedded dependency currently requires Python 3.12 or later.
from databend_driver import connect
# Persistent state stored under ./local-state
conn = connect("databend+local:///./local-state")
conn.exec("CREATE TABLE books(id INT, title STRING)")
conn.exec("INSERT INTO books VALUES (1, 'Databend')")
row = conn.query_row("SELECT title FROM books ORDER BY id LIMIT 1")
print(row.values()) # ('Databend',)
rows = [row.values() for row in conn.query_iter("SELECT * FROM books ORDER BY id")]
Supported local targets:
connect(":memory:") — temporary in-memory instance (discarded on close)
If the optional databend package is not installed, connect() raises an
ImportError with guidance about enabling the local extra and the Python
version requirement.
For remote Databend, the same connect() entrypoint accepts standard DSNs:
You can register files or in-memory data as virtual tables:
# Register a Parquet file
conn.register("sales", "./data/sales.parquet")
conn.sql("SELECT * FROM sales LIMIT 10").df()
# Register a CSV file
conn.register("events", "./data/events.csv")
# Register a pandas or polars DataFrame
import pandas as pd
df = pd.DataFrame({"id": [1, 2], "name": ["Alice", "Bob"]})
conn.register("users", df)
# Shorthand: register a DataFrame and return a relation immediately
relation = conn.from_df(df)
# Read helpers (register and return relation in one call)
relation = conn.read_parquet("./data/sales.parquet")
relation = conn.read_csv("./data/events.csv")
relation = conn.read_json("./data/logs.ndjson")
relation = conn.read_text("./data/raw.txt")
PEP 249 Cursor Object
from databend_driver import BlockingDatabendClient
client = BlockingDatabendClient("databend://root:root@localhost:8000/?sslmode=disable")
cursor = client.cursor()
cursor.execute(
"""
CREATE TABLE test (
i64 Int64,
u64 UInt64,
f64 Float64,
s String,
s2 String,
d Date,
t DateTime
)
"""
)
cursor.execute(
"INSERT INTO test VALUES (?, ?, ?, ?, ?, ?, ?)",
(1, 1, 1.0, "hello", "world", "2021-01-01", "2021-01-01 00:00:00"),
)
cursor.execute("SELECT * FROM test")
rows = cursor.fetchall()
for row in rows:
print(row.values())
cursor.close()
Blocking Connection Object
from databend_driver import BlockingDatabendClient
client = BlockingDatabendClient("databend://root:root@localhost:8000/?sslmode=disable")
conn = client.get_conn()
conn.exec(
"""
CREATE TABLE test (
i64 Int64,
u64 UInt64,
f64 Float64,
s String,
s2 String,
d Date,
t DateTime
)
"""
)
rows = conn.query_iter("SELECT * FROM test")
for row in rows:
print(row.values())
conn.close()
Asyncio Connection Object
import asyncio
from databend_driver import AsyncDatabendClient
async def main():
client = AsyncDatabendClient("databend://root:root@localhost:8000/?sslmode=disable")
conn = await client.get_conn()
await conn.exec(
"""
CREATE TABLE test (
i64 Int64,
u64 UInt64,
f64 Float64,
s String,
s2 String,
d Date,
t DateTime
)
"""
)
rows = await conn.query_iter("SELECT * FROM test")
async for row in rows:
print(row.values())
await conn.close()
asyncio.run(main())
Parameter bindings
# Positional parameters using ?
row = await context.conn.query_row("SELECT ?, ?, ?, ?", (3, False, 4, "55"))
# Named parameters using :name
row = await context.conn.query_row(
"SELECT :a, :b, :c, :d", {"a": 3, "b": False, "c": 4, "d": "55"}
)
# Single value (no tuple needed)
row = await context.conn.query_row("SELECT ?", 3)
# Keyword argument form
row = await context.conn.query_row("SELECT ?, ?, ?, ?", params=(3, False, 4, "55"))
Named parameters use token-aware matching, so :a will not corrupt :ab.
For local embedded connections, passing a mismatched number of ? placeholders
and values raises a ValueError immediately.
Query ID tracking and query management
# Get the last executed query ID
query_id = conn.last_query_id()
print(f"Last query ID: {query_id}")
# Execute a query and get its ID
await conn.query_row("SELECT 1")
query_id = conn.last_query_id()
print(f"Query ID: {query_id}")
# Kill a running query (if needed)
try:
await conn.kill_query("some-query-id")
print("Query killed successfully")
except Exception as e:
print(f"Failed to kill query: {e}")
CREATE TABLE example (
data VARIANT
);
INSERT INTO example VALUES ('{"a": 1, "b": "hello"}');
row = await conn.query_row("SELECT * FROM example limit 1;")
data = row.values()[0]
value = json.loads(data)
print(value)
GEOMETRY and GEOGRAPHY follow the current geometry_output_format setting. Text formats such as GeoJSON or WKT return str; binary formats such as WKB or EWKB return bytes.
The driver provides a complete set of exception classes that follow the PEP 249 standard for database interfaces:
# Base exceptions
class Warning(Exception): ...
class Error(Exception): ...
# Interface errors
class InterfaceError(Error): ...
# Database errors
class DatabaseError(Error): ...
# Specific database error types
class DataError(DatabaseError): ...
class OperationalError(DatabaseError): ...
class IntegrityError(DatabaseError): ...
class InternalError(DatabaseError): ...
class ProgrammingError(DatabaseError): ...
class NotSupportedError(DatabaseError): ...
These exceptions are automatically mapped from Databend error codes to appropriate PEP 249 exception types based on the nature of the error.
Note: stream_load and load_file support an optional method parameter, it accepts two string values:
stage: Data is first uploaded to a temporary stage and then loaded. This is the default behavior.
streaming: Data is directly streamed to the Databend server.