ClickHouse Driver

0.2.10 · active · verified Thu Apr 09

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

Install

Imports

Quickstart

This quickstart demonstrates how to connect to a ClickHouse server using the `Client`, execute simple queries, create a table, insert data using parameterization, and retrieve data. It emphasizes proper connection management and basic CRUD operations. Environment variables are used for connection details for better security and flexibility.

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.")

view raw JSON →