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; }
      }
相关推荐
沃和莱特3 分钟前
C++中类的继承
数据库·c++·编程·c·指针·友元函数
FF在路上19 分钟前
MySQL数据库-视图的介绍和使用
数据库·sql·mysql
数字扫地僧1 小时前
如何使用MySQL实现多租户架构:设计与实现全解析
数据库·mysql·架构
乄bluefox1 小时前
SpringBoot中使用Sharding-JDBC实战(实战+版本兼容+Bug解决)
java·数据库·spring boot·redis·后端·缓存·bug
尘佑不尘2 小时前
蓝队基础,了解企业安全管理架构
数据库·笔记·安全·web安全·蓝队
重生之我是数学王子2 小时前
QT 网络编程 数据库模块 TCP UDP QT5.12.3环境 C++实现
数据库·c++·qt·udp·tcp
running up that hill2 小时前
数据库中的增删改查操作、聚合函数、内置函数、分组查询
java·数据库·sql·mysql
莳花微语2 小时前
oracle如何配置第二个监听优化数据传输
数据库·oracle·php
小码的头发丝、2 小时前
Maven的安装与配置
java·数据库·maven
0zxm2 小时前
01.Django快速入门
数据库·vscode·python·django·sqlite