clickhouse数据库,http请求访问,支持参数化

csharp 复制代码
public class ClickHouseClient
{
    private static readonly HttpClient _httpClient = new HttpClient();
    private readonly string _clickHouseUrl;
    private readonly string _username;
    private readonly string _password;
    private string _database;
    private static readonly string _searchFormat = " FORMAT JSON";

    public ClickHouseClient()
    {
        _clickHouseUrl = "url";
        _username = "user_name";
        _password = "password";
        if (string.IsNullOrWhiteSpace(_clickHouseUrl) || string.IsNullOrWhiteSpace(_username) || string.IsNullOrWhiteSpace(_password))
        {
            System.Text.StringBuilder str = new System.Text.StringBuilder();
            str.Append("ClickHouse配置缺失,CloudStorage:ClickHouse");
            if (string.IsNullOrWhiteSpace(_clickHouseUrl))
            {
                str.Append("节点EndPoint,");
            }
            if (string.IsNullOrWhiteSpace(_username))
            {
                str.Append("节点UId,");
            }
            if (string.IsNullOrWhiteSpace(_password))
            {
                str.Append("节点Password,");
            }
            throw new Exception($"{str.ToString().TrimEnd(',')}未配置");
        }
        _database = "default";
        SetAuthorizationHeader();
    }

    /// <summary>
    /// 设置查询数据库
    /// </summary>
    /// <param name="database"></param>
    public void SetDatabase(string database)
    {
        _database = database;
        SetAuthorizationHeader();
    }

    /// <summary>
    /// 单个查询,参数化格式:sql语句中:{id:String},赋值:{"id","666"}
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="query"></param>
    /// <param name="parameters"></param>
    /// <returns></returns>
    public List<T> ExecuteQuery<T>(string query, Dictionary<string, string> parameters = null) where T : class
    {
        try
        {
            var response = SendRequest($"{query} {_searchFormat}", parameters);
            var responseString = response.Content.ReadAsStringAsync().Result;
            var data = System.Text.Json.JsonSerializer.Deserialize<ClickHouseBaseModel<T>>(responseString);
            return data?.data;
        }
        catch (HttpRequestException)
        {
            throw;
        }
    }

    /// <summary>
    /// 单条插入,参数化格式:sql语句中:{id:String},赋值:{"id","666"}
    /// </summary>
    /// <param name="query"></param>
    /// <param name="parameters"></param>
    public void ExecuteNonQuery(string query, Dictionary<string, string> parameters = null)
    {
        try
        {
            SendRequest(query, parameters);
        }
        catch (HttpRequestException)
        {
            throw;
        }
    }

    /// <summary>
    /// 设置访问信息
    /// </summary>
    private void SetAuthorizationHeader()
    {
        _httpClient.DefaultRequestHeaders.Clear();
        _httpClient.DefaultRequestHeaders.Add("X-ClickHouse-User", _username);
        _httpClient.DefaultRequestHeaders.Add("X-ClickHouse-Key", _password);
        _httpClient.DefaultRequestHeaders.Add("X-ClickHouse-Database", _database);
    }

    /// <summary>
    /// 进行访问
    /// </summary>
    /// <param name="query"></param>
    /// <param name="parameters"></param>
    /// <returns></returns>
    private HttpResponseMessage SendRequest(string query, Dictionary<string, string> parameters = null)
    {
        var formData = new MultipartFormDataContent
        {
            { new StringContent(query), "query" }
        };

        if (parameters != null)
        {
            foreach (var param in parameters)
            {
                string paramKey = param.Key;
                if (!param.Key.StartsWith("param_"))
                {
                    paramKey = $"param_{paramKey}";
                }

                formData.Add(new StringContent(param.Value), paramKey);
            }
        }

        var response = _httpClient.PostAsync(_clickHouseUrl, formData).Result;
        response.EnsureSuccessStatusCode();
        return response;
    }
}
csharp 复制代码
      public void TestClickHouse()
      {
          var client = new ClickHouseClient();
          client.SetDatabase("default");
          var sqlSearch = "select id Id, serial_number SerialNumber from test_table";
          var result = client.ExecuteQuery<TestTable>(sqlSearch);

          var sql = "insert into test_table(id,serial_number) values({id:String},{serial_number:UInt32})";
          var param = new Dictionary<string, string>()
          {
              {"id","777"},
              {"serial_number","1234"}
          };
          client.ExecuteNonQuery(sql, param);
      }

      public class TestTable
      {
          public string Id { get; set; }
          public long SerialNumber { get; set; }
      }
相关推荐
竹影卿心2 分钟前
Java连接HANA数据库
java·数据库·windows
anddddoooo5 分钟前
Kerberoasting 离线爆破攻击
网络·数据库·安全·microsoft·网络安全
time never ceases29 分钟前
Elasticsearch安装和数据迁移
大数据·数据库·elasticsearch·es
程序员shen1616111 小时前
注意⚠️:矩阵系统源码开发/SaaS矩阵系统开源/抖音矩阵开发优势和方向
java·大数据·数据库·python·php
IvorySQL1 小时前
2024 开放原子开发者大会活动回顾|瀚高 IvorySQL 开源数据库在国产软件的开源实践
数据库·postgresql·开源数据库·国产数据库·ivorysql
云计算DevOps-韩老师2 小时前
【网络云计算】2024第52周-每日【2024/12/26】小测-理论&实操-备份MySQL数据库并发送邮件-解析
linux·开发语言·网络·数据库·mysql·云计算·perl
2401_850410832 小时前
redis的持久化
数据库·redis·bootstrap
如雨随行20202 小时前
Mysql事务
数据库·mysql·oracle
未来并未来3 小时前
深入解析MVCC中Undo Log版本底层存储读取逻辑
java·数据库·mysql
菜还不练就废了3 小时前
Java期末复习JDBC|网课笔记+校课总结
java·开发语言·数据库