关于python与clickhouse的连接问题

首先说明,我的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不能读取字段名,需要自行设置。

两段代码都可以直接运行,要注意的就是出现连接不上的原因很有可能是你添加了端口号。我前面就参照别人的方法加了端口号,然后一直连不上,后面发现官方的代码中并没有端口号!

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值