ClickHouse Driver
clickhouse-driver is a Python driver for ClickHouse, implementing the native ClickHouse client-server protocol. It provides a synchronous interface for connecting to and interacting with ClickHouse databases. The current version is 0.2.10, and it generally sees periodic updates with several releases per year addressing bug fixes and Python version compatibility.
Warnings
- breaking Python version support has changed significantly. Versions 0.2.0 dropped Python 2 support. Version 0.2.9 dropped support for Python 3.6, 3.7, and 3.8. The current minimum supported Python version is 3.9.
- breaking Default connection parameters for `Client` changed in version 0.2.4. Specifically, `secure` now defaults to `False`, `port` defaults to `9000` (native protocol), and `compression` defaults to `False`. Previously, `secure` might have defaulted to `True` or different port values depending on prior library usage assumptions.
- gotcha The `clickhouse-driver` client does not include built-in connection pooling. For applications requiring high concurrency or frequent connections, you will need to implement a connection pool manually or use an external library.
- gotcha Always use parameterization for inserting data or executing queries with user-provided values to prevent SQL injection vulnerabilities. Direct string formatting of queries is insecure.
Install
-
pip install clickhouse-driver
Imports
- Client
from clickhouse_driver import Client
- errors
from clickhouse_driver import errors
Quickstart
import os
from clickhouse_driver import Client
# Ensure ClickHouse is running, e.g., with Docker:
# docker run -d --name clickhouse-server -p 8123:8123 -p 9000:9000 --ulimit nofile=262144:262144 yandex/clickhouse-server
host = os.environ.get('CLICKHOUSE_HOST', 'localhost')
port = int(os.environ.get('CLICKHOUSE_PORT', '9000')) # Default native protocol port
user = os.environ.get('CLICKHOUSE_USER', 'default')
password = os.environ.get('CLICKHOUSE_PASSWORD', '')
client = Client(host=host, port=port, user=user, password=password)
try:
# Execute a simple query
result = client.execute('SELECT 1 + 1 AS two')
print(f"Query result: {result}")
# Create a table and insert data
client.execute('DROP TABLE IF EXISTS test_data')
client.execute('CREATE TABLE test_data (id UInt64, name String) ENGINE = Memory')
data_to_insert = [(1, 'Alice'), (2, 'Bob'), (3, 'Charlie')]
client.execute('INSERT INTO test_data VALUES', data_to_insert)
print(f"Inserted {len(data_to_insert)} rows.")
# Select data
selected_data = client.execute('SELECT id, name FROM test_data ORDER BY id')
print(f"Selected data: {selected_data}")
finally:
client.disconnect()
print("Disconnected from ClickHouse.")