首先说明,我的clickhouse没有用户名和密码,所以后续不会讲到用户名与密码的相关添加方式。
参照clickhouse-driver · PyPI的代码方法,我成功将python与clickhouse连通。
我的版本——python3.8, clickhouse-driver0.2.4
clickhouse-driver我是直接相应环境里在anaconda里:
pip install clickhouse-driver
如果没有anaconda也可以直接在python环境命令行里敲上述命令安装也行。
方法一:客户端连接
import pandas as pd
from clickhouse_driver import Client
class PureClient:
def __init__(self):
# 只需要写本地地址
self.client = Client('xxx.xxx.x.xx')
# 如果要加数据库就用下面这句
# self.client = Client('xxx.xxx.x.xx', datebase = '数据库名')
# 直接查询且将查询结果放入dataframe(一种数据格式)里
def run(self, sql):
client = self.client
collection = client.query_dataframe(sql)
return collection
if __name__ == '__main__':
sql1 = "select * from 表名" # sql查询语句
clickhouse = PureClient()
result = clickhouse.run(sql1)
print(result)
这个方法可以直接读出有行列标识的df。
方法二:数据库连接
import pandas as pd
from clickhouse_driver import connect
class DbAPI:
def __init__(self):
# 只需要填写localhost,也可以加‘/数据库名’
conn = connect('clickhouse://xxx.xxx.x.xx/数据库名')
self.cursor = conn.cursor()
def run(self, sql):
cursor = self.cursor
cursor.execute(sql)
df = pd.DataFrame(cursor.fetchall())
return df
if __name__ == '__main__':
sql1 = "select * from 表名"
clickhouse = DbAPI()
result = clickhouse.run(sql1)
print(result)
这个方法读取的df不能读取字段名,需要自行设置。
两段代码都可以直接运行,要注意的就是出现连接不上的原因很有可能是你添加了端口号。我前面就参照别人的方法加了端口号,然后一直连不上,后面发现官方的代码中并没有端口号!