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
Useclickhouse_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, thesettings 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
localhostwith 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
Installclickhouse-connect[chdb] to use the experimental in-process chDB backend. It exposes the synchronous client query, insert, streaming, and Arrow methods:
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:Multi-threaded applications
To share a client across threads safely:Proper cleanup
Always close clients at shutdown. Note thatclient.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.
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 commonparameters and settings arguments. These keyword arguments are described below.
Parameters argument
ClickHouse Connect Clientquery* 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
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, theparameters 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
- Example with Python Sequence (Tuple), Float64, and IPv4Address
For a server-side For backward compatibility, a dictionary parameter name ending in
{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:_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 optionalsettings 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_set—result_rowsorresult_columns, according to the query orientation.column_names— Tuple of result column names.column_types— Tuple ofClickHouseTypeobjects.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 theX-ClickHouse-Summaryresponse header.first_item— First row as a dictionary, orNonefor an empty result.first_row— First row as a sequence, orNonefor an empty result.column_block_stream,row_block_stream, androws_stream— Internal stream contexts. Use the corresponding client streaming methods instead.
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 tableusers 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
Theclickhouse_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 stringclickhouse_connect.__version__.
Exceptions
Custom exceptions, including the DB-API 2.0 exception hierarchy, are defined inclickhouse_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 theclickhouse_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.