You need to enable JavaScript to run this app.
导航

ClickHouse Python Driver

最近更新时间2024.04.09 15:45:20

首次发布时间2023.12.18 12:14:26

本文介绍如何在 Python 开发环境连接并访问 ByteHouse 云数仓。
ByteHouse 兼容下列开源 ClickHouse Python Driver 程序:

  • mymarilyn/clickhouse-driver (非 Clickhouse 官方驱动,本文已在程序 0.2.6 版本下验证)

说明

需要 Python 3.7 或更高版本的支持。

前提条件

访问 ByteHouse 所需的连接信息,请参考 获取连接信息 获取。

程序安装

从 PyPI 安装

可以通过如下命令,获取最新发布版本的 clickhouse-driver。

pip3 install clickhouse-driver

从 github 安装

开发版本通过如下命令安装。

pip3 install git+https://github.com/mymarilyn/clickhouse-driver@master#egg=clickhouse-driver

安装依赖项

根据您的 Python 版本,您可能需要安装以下依赖项:

  1. pytz : 用于执行时区计算的 pytz 库;
  2. enum34 :用于支持 python 3.4 版本开始提供的内置枚举类。

连接示例

本章节介绍通过 mymarilyn/clickhouse-driver 程序连接 ByteHouse 的基本用法,您可以在程序 Github 主页 获取最新的文档和发布版本信息。

设置连接信息

可参考下面代码样例设置 ByteHouse 连接信息,具体内容可以根据前提条件中获取的信息填写。

# replace token here is the user api_key 
username, token = "bytehouse", "API_KEY" # Use {API_KEY} 
host, port = "localhost", 9000 # Use {HOST} and {PORT}
conn = connect(dsn=f'tcp://{username}:{token}@{host}:{port}?send_timeout=8000000&receive_timeout=80000')
cursor = conn.cursor()

基本用法示例

from clickhouse_driver import Client, connect

def connect_via_tcp():
    # replace token here is the user api_key 
    username, token = "bytehouse", "API_KEY" # Use {API_KEY} 
    host, port = "localhost", 9000 # Use {HOST} and {PORT}
    conn = connect(dsn=f'tcp://{username}:{token}@{host}:{port}?send_timeout=8000000&receive_timeout=80000')
    cursor = conn.cursor()

    cursor.execute("CREATE DATABASE databaseTest")
    print("create db: ", cursor.fetchall())

    cursor.execute("create table databaseTest.tablename  ( `col1` String ) ENGINE=CnchMergeTree PRIMARY KEY col1 ORDER BY col1")
    print("create tb: ", cursor.fetchall())

    cursor.executemany('INSERT INTO databaseTest.tablename (col1) values', [['python'], ['driver']])
    print("insert affect: ", cursor.rowcount)

    cursor.execute('SELECT * from databaseTest.tablename')
    print("select get: ", cursor.fetchall())

    cursor.execute("DROP DATABASE databaseTest")
    print("drop db: ", cursor.fetchall())


def main():
    connect_via_tcp()

if __name__ == "__main__":
    main()