Skip to main content
Passing keyword arguments is recommended for most api methods given the number of possible arguments, most of which are optional.Methods not documented here aren’t considered part of the API, and may be removed or changed.

Client Initialization

The clickhouse_connect.driver.client class provides the primary interface between a Python application and the ClickHouse database server. Use the clickhouse_connect.get_client function to obtain a Client instance, which accepts the following arguments:

Connection arguments

HTTPS/TLS arguments

Settings argument

Finally, the settings argument to get_client is used to pass additional ClickHouse settings to the server for each client request. Note that in most cases, users with readonly=1 access can’t alter settings sent with a query, so ClickHouse Connect will drop such settings in the final request and log a warning. The following settings apply only to HTTP queries/sessions used by ClickHouse Connect, and aren’t documented as general ClickHouse settings. For other ClickHouse settings that can be sent with each query, see the ClickHouse documentation.

Client creation examples

  • Without any parameters, a ClickHouse Connect client will connect to the default HTTP port on localhost with the default user and no password:
  • Connecting to a secure (HTTPS) external ClickHouse server
  • Connecting with a session ID and other custom connection parameters and ClickHouse settings.

Client Lifecycle and Best Practices

Creating a ClickHouse Connect client is an expensive operation that involves establishing a connection, retrieving server metadata, and initializing settings. Follow these best practices for optimal performance:

Core principles

  • Reuse clients: Create clients once at application startup and reuse them throughout the application lifetime
  • Avoid frequent creation: Don’t create a new client for each query or request (this wastes hundreds of milliseconds per operation)
  • Clean up properly: Always close clients when shutting down to release connection pool resources
  • Share when possible: A single client can handle many concurrent queries through its connection pool (see threading notes below)

Basic patterns

✅ Good: Reuse a single client
❌ Bad: Creating clients repeatedly

Multi-threaded applications

Client instances are NOT thread-safe when using session IDs. By default, clients have an auto-generated session ID, and concurrent queries within the same session will raise a ProgrammingError.
To share a client across threads safely:
Alternative for sessions: If you need sessions (e.g., for temporary tables), create a separate client per thread:

Proper cleanup

Always close clients at shutdown. Note that client.close() disposes the client and closes pooled HTTP connections only when the client owns its pool manager (for example, when created with custom TLS/proxy options). For the default shared pool, use client.close_connections() to proactively clear sockets; otherwise, connections are reclaimed automatically via idle expiration and at process exit.
Or use a context manager:

When to use multiple clients

Multiple clients are appropriate for:
  • Different servers: One client per ClickHouse server or cluster
  • Different credentials: Separate clients for different users or access levels
  • Different databases: When you need to work with multiple databases
  • Isolated sessions: When you need separate sessions for temporary tables or session-specific settings
  • Per-thread isolation: When threads need independent sessions (as shown above)

Common method arguments

Several client methods use one or both of the common parameters and settings arguments. These keyword arguments are described below.

Parameters argument

ClickHouse Connect Client query* and command methods accept an optional parameters keyword argument used for binding Python expressions to a ClickHouse value expression. Two sorts of binding are available.

Server-side binding

ClickHouse supports server side binding for most query values, where the bound value is sent separate from the query as an HTTP query parameter. ClickHouse Connect will add the appropriate query parameters if it detects a binding expression of the form {<name>:<datatype>}. For server side binding, the parameters argument should be a Python dictionary.
  • Server-side binding with Python dictionary, DateTime value, and string value
This generates the following query on the server:
Server-side binding is only supported (by the ClickHouse server) for SELECT queries. It doesn’t work for ALTER, DELETE, INSERT, or other types of queries. This may change in the future; see https://github.com/ClickHouse/ClickHouse/issues/42092.

Client-side binding

ClickHouse Connect also supports client-side parameter binding, which can allow more flexibility in generating templated SQL queries. For client-side binding, the parameters argument should be a dictionary or a sequence. Client-side binding uses the Python “printf” style string formatting for parameter substitution. Note that unlike server-side binding, client-side binding doesn’t work for database identifiers such as database, table, or column names, since Python-style formatting can’t distinguish between the different types of strings, and they need to be formatted differently (backticks or double quotes for database identifiers, single quotes for data values).
  • Example with Python Dictionary, DateTime value and string escaping
This generates the following query on the server:
  • Example with Python Sequence (Tuple), Float64, and IPv4Address
This generates the following query on the server:
To bind DateTime64 arguments (ClickHouse types with sub-second precision) requires one of two custom approaches:
  • Wrap the Python datetime.datetime value in the new DT64Param class, e.g.
    • If using a dictionary of parameter values, append the string _64 to the parameter name

Settings argument

All the key ClickHouse Connect Client “insert” and “select” methods accept an optional settings keyword argument to pass ClickHouse server user settings for the included SQL statement. The settings argument should be a dictionary. Each item should be a ClickHouse setting name and its associated value. Note that values will be converted to strings when sent to the server as query parameters. As with client level settings, ClickHouse Connect will drop any settings that the server marks as readonly=1, with an associated log message. Settings that apply only to queries via the ClickHouse HTTP interface are always valid. Those settings are described under the get_client API. Example of using ClickHouse settings:

Client command Method

Use the Client.command method to send SQL queries to the ClickHouse server that don’t normally return data or that return a single primitive or array value rather than a full dataset. This method takes the following parameters:

Command examples

DDL statements

Simple queries returning single values

Commands with parameters

Commands with settings

Client query Method

The Client.query method is the primary way to retrieve a single “batch” dataset from the ClickHouse server. It utilizes the Native ClickHouse format over HTTP to transmit large datasets (up to approximately one million rows) efficiently. This method takes the following parameters:

Query examples

Basic query

Accessing query results

Query with client-side parameters

Query with server-side parameters

Query with settings

The QueryResult object

The base query method returns a QueryResult object with the following public properties:
  • result_rows — A matrix of the data returned in the form of a Sequence of rows, with each row element being a sequence of column values.
  • result_columns — A matrix of the data returned in the form of a Sequence of columns, with each column element being a sequence of the row values for that column
  • column_names — A tuple of strings representing the column names in the result_set
  • column_types — A tuple of ClickHouseType instances representing the ClickHouse data type for each column in the result_columns
  • query_id — The ClickHouse query_id (useful for examining the query in the system.query_log table)
  • summary — Any data returned by the X-ClickHouse-Summary HTTP response header
  • first_item — A convenience property for retrieving the first row of the response as a dictionary (keys are column names)
  • first_row — A convenience property to return the first row of the result
  • column_block_stream — A generator of query results in column oriented format. This property shouldn’t be referenced directly (see below).
  • row_block_stream — A generator of query results in row oriented format. This property shouldn’t be referenced directly (see below).
  • rows_stream — A generator of query results that yields a single row per invocation. This property shouldn’t be referenced directly (see below).
  • summary — As described under the command method, a dictionary of summary information returned by ClickHouse
The *_stream properties return a Python Context that can be used as an iterator for the returned data. They should only be accessed indirectly using the Client *_stream methods. The complete details of streaming query results (using StreamContext objects) are outlined in Advanced Queries (Streaming Queries).

Consuming query results with NumPy, Pandas or Arrow

ClickHouse Connect provides specialized query methods for NumPy, Pandas, and Arrow data formats. For detailed information on using these methods, including examples, streaming capabilities, and advanced type handling, see Advanced Querying (NumPy, Pandas and Arrow Queries).

Client streaming query methods

For streaming large result sets, ClickHouse Connect provides multiple streaming methods. See Advanced Queries (Streaming Queries) for details and examples.

Client insert Method

For the common use case of inserting multiple records into ClickHouse, there is the Client.insert method. It takes the following parameters: This method returns a “query summary” dictionary as described under the “command” method. An exception will be raised if the insert fails for any reason. For specialized insert methods that work with Pandas DataFrames, PyArrow Tables, and Arrow-backed DataFrames, see Advanced Inserting (Specialized Insert Methods).
A NumPy array is a valid Sequence of Sequences and can be used as the data argument to the main insert method, so a specialized method isn’t required.

Examples

The examples below assume an existing table users with schema (id UInt32, name String, age UInt8).

Basic row-oriented insert

Column-oriented insert

Insert with explicit column types

Insert into specific database

File Inserts

For inserting data directly from files into ClickHouse tables, see Advanced Inserting (File Inserts).

Raw API

For advanced use cases requiring direct access to ClickHouse HTTP interfaces without type transformations, see Advanced Usage (Raw API).

Utility classes and functions

The following classes and functions are also considered part of the “public” clickhouse-connect API and are, like the classes and methods documented above, stable across minor releases. Breaking changes to these classes and functions will only occur with a minor (not patch) release and will be available with a deprecated status for at least one minor release.

Exceptions

All custom exceptions (including those defined in the DB API 2.0 specification) are defined in the clickhouse_connect.driver.exceptions module. Exceptions actually detected by the driver will use one of these types.

ClickHouse SQL utilities

The functions and the DT64Param class in the clickhouse_connect.driver.binding module can be used to properly build and escape ClickHouse SQL queries. Similarly, the functions in the clickhouse_connect.driver.parser module can be used to parse ClickHouse datatype names.

Multithreaded, multiprocess, and async/event driven use cases

For information on using ClickHouse Connect in multithreaded, multiprocess, and async/event-driven applications, see Advanced Usage (Multithreaded, multiprocess, and async/event driven use cases).

AsyncClient wrapper

For information on using the AsyncClient wrapper for asyncio environments, see Advanced Usage (AsyncClient wrapper).

Managing ClickHouse Session IDs

For information on managing ClickHouse session IDs in multi-threaded or concurrent applications, see Advanced Usage (Managing ClickHouse Session IDs).

Customizing the HTTP connection pool

For information on customizing the HTTP connection pool for large multi-threaded applications, see Advanced Usage (Customizing the HTTP connection pool).
Last modified on June 12, 2026