1. 背景-问题描述
最近做一个资产数据清洗工作,结束后需要将数据批量插入到clickhouse;查找并尝试了好几种批量插入的方式均已失败告终;现就查到的dataframe类型数据批量插入到clickhouse记录和汇总于此。
2. 配置信息
python 3.12
clickhouse_driver 0.2.9
PyYAML 6.0.2
pandas 2.2.3
numpy 2.1.2
3. 单条数据插入
from clickhouse_driver import Client
client = Client(
host='host',
port='port',
user='user',
password='password',
settings={
'use_numpy': True}
)
# 创建表格
client.execute("CREATE TABLE IF NOT EXISTS db.test_table (id Int32, name String) ENGINE = MergeTree")
sql = "INSERT INTO db.test_table (id, name) VALUES (1, 'test_1')"
client.execute(sql)
db.test_table: db表示数据库,test_table表示表名称
4. 多条数据插入
# 多条数据插入
sql = "INSERT INTO db.test_table (id, name) VALUES (1, 'test_1'), (2, 'test_2')"
client.execute(sql)
5. dataframe数据全部插入
5.1 将需要插入的数据写入到sql中
# 取出dataframe列
import pandas as pd
import numpy as np
from clickhouse_driver import Client
client = Client(
host='host',
port='port',
user='user',
password='password',
settings={
'use_numpy': True}
)
# 创建一个示例DataFrame
data = {
'id': [1, 2, 3],
'name': ['name_1', 'name_2', 'name_3']
}
df = pd.DataFrame(data)
cols = df.columns.tolist()
sql0 = f"INSERT INTO db.test_table ({
','.join(map(str, cols))}) VALUES"
# 将df下的values转化为tuple格式: [(1, 'name_1'), (2, 'name_2'),(3, 'name_3')]
tuples = [tuple(x) for x in df.to_numpy()]
sql = f"{
sql0}" + ', '.join(map(str, tuples))
client.execute(sql)
5.2 使用insert_dataframe
cols = df.columns.tolist()
query = f"INSERT INTO {
table