1.添加依赖
ClickHouse.Ado
2.编写工具类
using ClickHouse.Ado;
using System.Data;
namespace clickhouse.config
{
public class CKHelper
{
private static ClickHouseConnection? _clickHouseConnection;
private static string _clickHouseConnectionString = "Compress=True;CheckCompressedHash=False;Compressor=lz4;Host=xxx;Port=9000;User=default;Password=;SocketTimeout=600000;Database=xxx;";
private static ClickHouseConnection GetClickhouseConnection()
{
if (_clickHouseConnection == null)
{
var settings = new ClickHouseConnectionSettings(_clickHouseConnectionString);
var cnn = new ClickHouseConnection(settings);
if (cnn.State != ConnectionState.Open)
{
cnn.Open();
}
_clickHouseConnection = cnn;
}
return _clickHouseConnection;
}
public static object Select(string sql)
{
var conn = GetClickhouseConnection();
IDataReader reader=conn.CreateCommand(sql).ExecuteReader();
return PrintData(reader);
}
private static string PrintData(IDataReader reader)
{
var res = "";
do
{
while (reader.Read())
{
for (var i = 0; i < reader.FieldCount; i++)
{
var val = reader.GetValue(i);
Console.Write(val);
Console.Write(", ");
res += val + ", ";
}
Console.WriteLine();
res += "\n";
}
Console.WriteLine();
} while (reader.NextResult());
return res;
}
public static object Insert(string sql)
{
return GetClickhouseConnection().CreateCommand(sql).ExecuteNonQuery();
}
}
}
3.测试
using clickhouse.config;
using Microsoft.AspNetCore.Mvc;
namespace clickhouse.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class MyController : ControllerBase
{
[HttpGet(Name = "my")]
public object Get()
{
//插入
//CKHelper.Insert("insert into tran_request_slow_record(api,param,create_time,time) values ('123321','参数',NOW(),6);");
//查询
var result = CKHelper.Select("select * from tran_request_slow_record limit 10");
return result;
}
}
}