最近更新时间:2024.04.09 15:45:20
首次发布时间:2023.12.18 12:14:26
本文介绍如何在 Python 开发环境连接并访问 ByteHouse 云数仓。
ByteHouse 兼容下列开源 ClickHouse Python Driver 程序:
说明
需要 Python 3.7 或更高版本的支持。
访问 ByteHouse 所需的连接信息,请参考 获取连接信息 获取。
可以通过如下命令,获取最新发布版本的 clickhouse-driver。
pip3 install clickhouse-driver
开发版本通过如下命令安装。
pip3 install git+https://github.com/mymarilyn/clickhouse-driver@master#egg=clickhouse-driver
根据您的 Python 版本,您可能需要安装以下依赖项:
本章节介绍通过 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()