(作者:陈玓玏)
使用clickhouse-driver包,先通过pip install clickhouse-driver安装包,再通过以下代码执行sql。
from clickhouse_driver import Client
client = Client(host='10.43.234.214', port=9000, user='clickhouse', password='c1ickh0use0perator')# 执行一个创建数据库的语句
#query = 'create table cdl'
#result = client.execute(query)# 执行一个创建表的语句
query = '''CREATE TABLE IF NOT EXISTS cdl.star
(week Int32,star Int32
)ENGINE = MergeTree()
ORDER BY week
PARTITION BY week
PRIMARY KEY week'''
result = client.execute(query)data = [{'week': 1, 'star': 1},{'week': 2, 'star': 10},{'week': 3, 'star': 100},{'week': 4, 'star': 300},{'week': 5, 'star': 500},{'week': 6, 'star': 1000}
]
#执行插入语句
query = "INSERT INTO cdl.star VALUES" + ','.join(["(%s,%s)" % (d['week'], d['star']) for d in data])
result = client.execute(query)#执行查询
query = 'select * from cdl.star limit 10'
result = client.execute(query)# 打印结果
for row in result:print(row)