python连接clickhouse

Python 连接clickhouse 成功连接并输出数据 避坑

      • 需要准备的package
    • 连接数据库
    • 读取数据
      • 需要的包
      • 导出文件
    • Reference

需要准备的package

clickhouse驱动程序

pip install clickhouse-driver
pip install clickhouse-driver[numpy]
pip install openpyxl
pip install Pillow

这里下载的时候会报错 如果报错了就打开管理模式再进行下载

开始搜索了很多方式但是有几个方式连接出来之后后续的输出时候存在一些问题 选取了成功的一种方式展现

from clickhouse_diver import Client #连接数据库

连接数据库

host='(clickhouse的ip)' 
port=(连接端口) 
username='' 
password='' 
database='(连接的数据库)' 
send_receive_timeout = 5

'''
成功登录的信息
client = Client(host=host, port=port, user=username, password=password)
'''
client = Client(host, settings={'use_numpy': True})

這是之前嘗試的失敗案例 顯示了目標計算機拒絕訪問

#目标计算机拒接访问连接  (:9440) 打开了口子 但是还是显示拒绝了
#Clickhouse server settings: https://clickhouse.com/docs/en/operations/settings/settings
localhost=''
settings = {'max_threads': 2 }
client = Client(localhost,secure=True,settings=settings)

如何設置以及計算機會訪問的端口都在官方的文檔 Clickhouse server settings中可以查詢到

读取数据

需要的包

from pandas as pd #数据操作相关
from clickhouse_sqlalchemy import make_session #数据库相关
from sqlalchemy import create_engine #数据库相关
from decimal import * #数据操作相关
from pandas import DataFrame #数据操作相关

官网中给出了很多种方法 我选择了使用panda包中的query_dataframe()函数来操作 输出的是dataframe

sql1='SELECT * from tb where date>\'2022-01-01\' and date<\'2022-02-01\' order by date desc limit 100'

result=client.query_dataframe(sql1) # 无法转换Decimal(16, 2)数据类型的内容 直接输出了Decimal内部的数
print(result)# 查询结果 输出的是dataframe的数据结构
print('=============================================')
element = result.loc[0] # 里面的元素需要通过这种方式输出单个的对象
print(element)
print('=============================================')
print(result.loc[0,'id']) 每个对象的特性的值
print(result[['id']]) #输出那一列

官网提供的execute()函数输出的是array

result1=client.execute(sql1) #查询结果输出的是array
print('=============================================')
print(result1) # 查询结果 输出的是 二维数组
print(result1[2]) #数组 
print(result1[2][0])

导出文件

简单的把数据输出到excel当中去

result.to_excel('(输出的文件名称)', index = False)

格式化输出可以查看https://www.biaodianfu.com/pandas-excel-csv.html

Reference

https://clickhouse-driver.readthedocs.io/en/latest/features.html#python-db-api-2-0

https://pypi.org/project/clickhouse-driver/

https://clickhouse.com/docs/en/operations/settings/settings

https://pandas.pydata.org/docs/referenc/api/pandas.DataFrame.query.html

https://www.biaodianfu.com/pandas-excel-csv.html

你可能感兴趣的:(python,python,clickhouse,数据分析,大数据,numpy)