ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

python连接clickhouse常用的三种方式

2022-06-30 12:00:26  阅读:495  来源: 互联网

标签:sqlalchemy python xxx cursor session 三种 import clickhouse


推荐运行环境

  • python 3.8.3
  • clickhouse_driver==0.2.3
  • clickhouse_sqlalchemy==0.2.0
  • sqlalchemy==1.4.32

一、clickhouse_driver连接的两种方式

注意端口都使用tcp端口9000

1.Client

from clickhouse_driver import Client

client = Client(host=host, port=9000, database=database,user=user ,password=pw)
sql = 'SHOW TABLES'
res = client.execute(sql)

 

2.connect

from clickhouse_driver import connect

#账号:密码@主机名:端口号/数据库
conn = connect(f'clickhouse://{user}:{pw}@{host}:9000/{database}')
cursor = conn.cursor()
cursor.execute('SHOW TABLES')

 

二、clickhouse_sqlalchemy连接方式

使用较复杂,推荐使用上述两种,注意使用端口为http端口8123。

from clickhouse_sqlalchemy import make_session
from sqlalchemy import create_engine
import pandas as pd

conf = {
    "user": "xxx",
    "password": "xxx",
    "server_host": "xx.xxx.xx.xxx",
    "port": "8123",
    "db": "xxx"
}

connection = 'clickhouse://{user}:{password}@{server_host}:{port}/{db}'.format(**conf)
engine = create_engine(connection, pool_size=100, pool_recycle=3600, pool_timeout=20)

sql = 'SHOW TABLES'

session = make_session(engine)
cursor = session.execute(sql)
try:
    fields = cursor._metadata.keys
    df = pd.DataFrame([dict(zip(fields, item)) for item in cursor.fetchall()])
finally:
    cursor.close()
    session.close()

 

标签:sqlalchemy,python,xxx,cursor,session,三种,import,clickhouse
来源: https://www.cnblogs.com/MrYang-11-GetKnow/p/16426373.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有