不多废话直接上代码后续大家看代码自己理解吧,本次实现的是批量导入的功能直接读取指定文件夹下所有的sql文件

import os
import requests
from requests.auth import HTTPBasicAuth
import time


def load_sql_to_clickhouse_with_retry(sql_file_path, clickhouse_url, database, username, password, timeout=30, retries=3, delay=5):
    for attempt in range(retries):
        try:
            # 读取 SQL 文件
            with open(sql_file_path, 'r', encoding='utf-8') as file:
                sql_query = file.read()

            # 构建请求 URL
            url = f'{clickhouse_url}/?database={database}'

            # 设置 HTTPBasicAuth (用户名和密码)
            auth = HTTPBasicAuth(username, password)

            # 发送 HTTP 请求,连接超时为 timeout 秒
            response = requests.post(url, data=sql_query, auth=auth, timeout=timeout)

            # 检查响应状态
            if response.status_code == 200:
                print(f"SQL 文件 {sql_file_path} 已成功导入.")
                return  # 如果成功,跳出循环
            else:
                print(f"执行查询失败. 文件: {sql_file_path}, 状态码: {response.status_code}")
                print("响应内容:", response.text)
                return

        except requests.exceptions.RequestException as e:
            print(f"尝试 {attempt + 1}/{retries} 导入文件 {sql_file_path} 时发生错误: {e}")
            if attempt < retries - 1:  # 不是最后一次重试时,延迟重试
                time.sleep(delay)
            else:
                print("重试次数已达到最大限制,跳过此文件。")
        except Exception as e:
            print(f"处理文件 {sql_file_path} 时发生了未知错误: {e}")
            break  # 出现未知错误,跳出循环


# 文件夹路径
folder_path = r'C:\Users\W10LL\Documents\WeChat Files\wxid_0k6xar6zixmy22\FileStorage\File\clickhouse'  #你可以自定义sql文件存储位置直接写你SQL文件所在文件夹即,代码会自动读取的

# ClickHouse 信息
clickhouse_url = 'http://地址:端口'  # 请替换为实际的 ClickHouse 地址和端口
database = 'xx'  # 请替换为你的数据库名称
username = 'user'  # 请替换为实际的用户名
password = 'passwd'  # 请替换为实际的密码

# 遍历文件夹中的 .sql 文件并导入
for filename in os.listdir(folder_path):
    if filename.endswith('.sql'):  # 如果文件是 .sql 文件
        sql_file_path = os.path.join(folder_path, filename)  # 拼接完整路径
        print(f"正在导入文件: {sql_file_path}")

        # 调用函数进行 SQL 导入
        load_sql_to_clickhouse_with_retry(sql_file_path, clickhouse_url, database, username, password)

print("所有文件导入完成.")

Logo

码道开发者社区,聚焦华为云码道 CodeArts 代码智能体,沉淀 Agent、Skill、鸿蒙开发实战内容,供开发者查阅资料、交流技术、分享工程实践

更多推荐