Skip to main content
Pass arguments by keyword for client factories and methods with many optional parameters.Methods not documented here aren’t considered part of the API, and may be removed or changed.

Client initialization

Use clickhouse_connect.get_client to create a synchronous Client, or install the async extra and await clickhouse_connect.get_async_client to create a native AsyncClient.

Connection arguments

The async factory also accepts connector_limit=100, connector_limit_per_host=20, and keepalive_timeout=30.0 to configure its aiohttp connection pool. It does not accept pool_mgr. The synchronous chDB backend accepts path and chdb_options; see Embedded chDB backend.

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.

Embedded chDB backend

Install clickhouse-connect[chdb] to use the experimental in-process chDB backend. It exposes the synchronous client query, insert, streaming, and Arrow methods:
The default is an in-memory database. Pass path="/data/my_chdb" or use dsn="chdb:///data/my_chdb" for persistent storage. The backend allows one engine path per process and does not support get_async_client or external data.

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
  • 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

Reuse a single client:
Avoid 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 query values. The bound value is sent separately from the query as an HTTP parameter. ClickHouse Connect uses this mode when it detects an expression of the form {<name>:<datatype>}. Pass the values as a Python dictionary.
  • Server-side binding with Python dictionary, DateTime value, and string value
This is equivalent to:
Server-side binding is supported for SELECT queries. It doesn’t work for ALTER, DELETE, INSERT, or other statement types.

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:
For a server-side {value:DateTime64(precision)} placeholder, the declared type preserves sub-second precision automatically, including inside Array and Tuple hints.Client-side %s binding has no declared type. Wrap a datetime in DT64Param when it must render with sub-second precision:
For backward compatibility, a dictionary parameter name ending in _64 also requests DateTime64 formatting when that exact suffixed name is not present in the query.

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 Client.command for statements that don’t return a tabular dataset, or for queries that return one primitive value or one row. Depending on the response, it returns a string, integer, sequence of strings, or QuerySummary. A read that produces an empty result set returns an empty string.

Command examples

DDL statements

Simple queries returning single values

Commands with parameters

Commands with settings

Client query method

Client.query retrieves a tabular dataset in ClickHouse Native format and returns a QueryResult. The complete result is materialized when a result property is accessed. Use a streaming method for results that should not be held in memory.

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 — Result matrix oriented as rows.
  • result_columns — Result matrix oriented as columns.
  • result_setresult_rows or result_columns, according to the query orientation.
  • column_names — Tuple of result column names.
  • column_types — Tuple of ClickHouseType objects.
  • row_count — Number of materialized result rows.
  • query_id — Query ID reported or generated for the request. An empty string means none was available.
  • summary — Dictionary decoded from the X-ClickHouse-Summary response header.
  • first_item — First row as a dictionary, or None for an empty result.
  • first_row — First row as a sequence, or None for an empty result.
  • column_block_stream, row_block_stream, and rows_stream — Internal stream contexts. Use the corresponding client streaming methods instead.
See Streaming queries for the supported StreamContext APIs.

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 QuerySummary. Its summary dictionary contains values reported by the server. written_rows is a convenience property, while written_bytes() and query_id() return the corresponding values. An insert failure raises an exception. 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).

Python DB-API 2.0

The clickhouse_connect.dbapi module implements the PEP 249 connection and cursor interface. It declares API level 2.0, threadsafety=2, and paramstyle="pyformat".
Cursor.execute and Cursor.executemany accept an additional settings keyword argument for ClickHouse settings. executemany uses the driver’s Native bulk-insert path for compatible INSERT ... VALUES statements with a materialized sequence of rows. fetchone, fetchmany, and fetchall consume the current materialized result. ClickHouse does not provide traditional transactions through this HTTP interface. Connection.commit() and Connection.rollback() are no-ops. The session ID concurrency rules still apply when a connection is shared.

Utility classes and functions

The following modules provide additional public helpers used by client applications. The installed package version is exposed as the string clickhouse_connect.__version__.

Exceptions

Custom exceptions, including the DB-API 2.0 exception hierarchy, are defined in clickhouse_connect.driver.exceptions. DatabaseError and OperationalError expose a numeric code attribute with the ClickHouse error code and a name attribute with the symbolic name such as UNKNOWN_TABLE, so applications can branch on exc.code instead of parsing the message. code is set even when show_clickhouse_errors is disabled, while name requires it. Both are None when unavailable, such as on transport errors. A connection failure partway through reading a query result raises StreamFailureError rather than returning a truncated result.

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

For native asyncio usage, see Advanced Usage (AsyncClient).

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 July 23, 2026