You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何查看ClickHouse端口号并使用Python导入CSV文件

ClickHouse端口号查询与Python导入CSV方法

一、查询ClickHouse端口号

SHOW SETTINGS 命令仅展示会话或系统级配置参数,不会返回服务监听的端口号。以下是几种可靠的查询方式:

1. 查看配置文件

ClickHouse的端口配置默认存储在主配置文件中:

  • Linux系统路径通常为 /etc/clickhouse-server/config.xml,Windows则对应安装路径下的config.xml
  • 打开文件后查找对应标签:
    • <tcp_port>:TCP协议端口(默认9000,用于原生客户端连接,是导入数据的常用端口)
    • <http_port>:HTTP协议端口(默认8123,用于HTTP接口访问)
    • <interserver_http_port>:集群节点间通信端口(默认9009)

2. 用系统命令查看监听端口

在Linux终端执行以下命令,查看ClickHouse进程正在监听的端口:

netstat -tulpn | grep clickhouse-server
# 或更高效的ss命令
ss -tulpn | grep clickhouse-server

输出中LISTEN状态对应的端口即为当前ClickHouse正在使用的端口。

3. 默认端口参考

若未修改过配置,ClickHouse默认端口为:

  • TCP:9000
  • HTTP:8123

二、Python导入CSV到ClickHouse

以下是三种常用的实现方式:

方法1:使用clickhouse-driver(TCP协议,性能优先)

clickhouse-driver是官方推荐的Python客户端,适合批量导入数据。

  1. 安装依赖:
pip install clickhouse-driver
  1. 示例代码:
from clickhouse_driver import Client
import csv

# 连接ClickHouse
client = Client(
    host='localhost',
    port=9000,  # 替换为你的TCP端口
    user='default',
    password='',
    database='your_database'
)

# 创建目标表(若不存在)
create_table_sql = """
CREATE TABLE IF NOT EXISTS your_table (
    id UInt32,
    name String,
    value Float64
) ENGINE = MergeTree()
ORDER BY id
"""
client.execute(create_table_sql)

# 读取CSV并批量导入
with open('data.csv', 'r', encoding='utf-8') as f:
    reader = csv.reader(f)
    next(reader)  # 跳过表头(CSV有表头时启用)
    client.execute(
        'INSERT INTO your_table VALUES',
        [tuple(row) for row in reader],
        types_check=True  # 可选,开启字段类型校验
    )

client.disconnect()

方法2:使用requests(HTTP协议,轻量便捷)

通过ClickHouse的HTTP接口导入,适合快速测试或小批量数据。

  1. 安装依赖:
pip install requests
  1. 示例代码:
import requests

# 配置信息
CLICKHOUSE_HOST = 'localhost'
CLICKHOUSE_PORT = 8123
DATABASE = 'your_database'
TABLE = 'your_table'
CSV_PATH = 'data.csv'

# 构建请求URL
url = f'http://{CLICKHOUSE_HOST}:{CLICKHOUSE_PORT}/?database={DATABASE}&query=INSERT INTO {TABLE} FORMAT CSV'

# 发送导入请求
with open(CSV_PATH, 'rb') as f:
    response = requests.post(url, data=f)

# 校验结果
if response.status_code == 200:
    print('数据导入成功')
else:
    print(f'导入失败:{response.text}')

提示:若CSV包含表头,需将FORMAT CSV改为FORMAT CSVWithNames,并确保表头与表字段名一致。

方法3:结合Pandas导入(结构化数据快速处理)

适合处理带复杂结构的CSV,一键完成读取+导入流程:

  1. 安装依赖:
pip install clickhouse-driver pandas
  1. 示例代码:
import pandas as pd
from clickhouse_driver import Client

# 连接ClickHouse
client = Client(host='localhost', port=9000, database='your_database')

# 读取CSV到DataFrame
df = pd.read_csv('data.csv')

# 将DataFrame写入ClickHouse
client.execute(
    'INSERT INTO your_table VALUES',
    df.to_records(index=False).tolist()
)

内容的提问来源于stack exchange,提问作者Suhas T

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 03:05:30