C# 连接Influxdb时序数据库的方法总结,其中包括初始化,连接,读取,写入等方法。
using InfluxDB.Client;
using InfluxDB.Client.Api.Domain;
using InfluxDB.Client.Core.Flux.Domain;
using InfluxDB.Client.Linq;
using InfluxDB.Client.Writes;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using static DataBaseDll.Constant;
using static DataBaseDll.Method;
namespace DataBaseDll
{
///
/// InfluxDB辅助器
///
[Serializable]
public class InfluxDBHelper : TimescaleBase
{
#region 属性
///
/// 组织
///
public string Org { get; set; } = string.Empty;
///
/// 令牌
///
public string Token { get; set; } = string.Empty;
///
/// 是否验证令牌
///
public bool IsAuthenticateToken { get; set; } = false;
///
/// SQL语句最大数量
///
public int MaxSQLTextCount { get; set; } = 10000;
///
/// 客户端
///
[field: NonSerialized()]
public InfluxDBClient Client { get; set; } = null;
#endregion
#region 构造函数
///
/// 构造函数
///
/// 用户名
/// 密码
/// 令牌
/// 组织
/// 库名
/// IP
/// 端口
public InfluxDBHelper(string userName, string password, string token, string org, string dbName,
string ip = LocalHost, int port = 8086, int timeOut = 10, bool isAuthenticateToken = true)
{
IP = ip;
Port = port;
UserName = userName;
Password = password;
DBName = dbName;
Token = token;
IsAuthenticateToken = isAuthenticateToken;
Org = org;
TimeOut = timeOut;
}
#endregion
#region 方法
#region 连接
///
/// 连接
///
/// 错误字符串
/// 连接是否成功
public bool Connect(out string errorString)
{
//初始化
errorString = string.Empty;
//检查连接
if (CheckPort(IP, Port))
{
InfluxDBClientOptions.Builder builder = new InfluxDBClientOptions.Builder().
Url($"http://{IP}:{Port}").
TimeOut(TimeSpan.FromSeconds(TimeOut));
Client = Client ?? InfluxDBClientFactory.Create(IsAuthenticateToken ? builder.AuthenticateToken(Token).Build() : builder.Authenticate(UserName, Password.ToString().ToArray()).Build());
if (Client == null)
{
errorString = "无法创建InfluxDB客户端!\n";
}
}
else
{
errorString = $"{IP}:{Port}无法连接!\n";
}
return string.IsNullOrEmpty(errorString);
}
///
/// 断开
///
/// 错误字符串
/// 断开是否成功
public bool Disconnect(out string errorString)
{
//初始化
errorString = string.Empty;
Client.Dispose();
Client = null;
return string.IsNullOrEmpty(errorString);
}
#endregion
#region
///
/// 根据SQL语句写入数据库
///
/// SQL语句
/// 错误字符串
/// 写入是否成功
public bool Write(string sqlText, out string errorString)
{
//初始化
errorString = string.Empty;
//检查参数
if (string.IsNullOrEmpty(sqlText))
{
errorString = $"查询语句为空!\n";
return false;
}
//检查连接
if (!Connect(out errorString))
{
return false;
}
using (WriteApi writeApi = Client.GetWriteApi())
{
writeApi.WriteRecord(sqlText, WritePrecision.Ns, DBName, Org);
}
return string.IsNullOrEmpty(errorString);
}
///
/// 写入数据
///
/// 点数据列表
/// 错误字符串
/// 是否写入成功
public bool Write(List pointDataList, out string errorString)
{
//初始化
errorString = string.Empty;
//检查参数
if (pointDataList == null || !pointDataList.Any())
{
errorString = $"写入数据为空!\n";
return false;
}
//检查连接
if (!Connect(out string errorstr))
{
errorString = errorstr;
return false;
}
using (WriteApi writeApi = Client.GetWriteApi())
{
writeApi.WritePoints(pointDataList, DBName, Org);
}
return string.IsNullOrEmpty(errorString);
}
///
/// 查询指定条件的数据个数,使用外部委托参数时效率不高
///
/// InfluxDB数据类型
///
/// 起始时间
/// 终止时间
/// 个数
/// 错误字符串
/// 是否读取成功
public bool GetCount(out int count, out string errorString, Func func = null, DateTime? startTime = null, DateTime? endTime = null)
where InfluxDBDataT : InfluxDBDataBase
{
//初始化
count = 0;
errorString = string.Empty;
List influxDBDataTList = new List();
//检查连接
if (!Connect(out string str))
{
errorString = str;
return false;
}
try
{
influxDBDataTList = InfluxDBQueryable.Queryable(DBName, Org, Client.GetQueryApiSync()).
Where(p => (startTime == null || p.Timestamp.ToLocalTime() >= (DateTime)startTime) &&
(endTime == null || p.Timestamp.ToLocalTime() <= (DateTime)endTime)).ToList();
}
catch (Exception ex)
{
errorString = $"查询失败!{ex.Message}。\n";
return false;
}
count = influxDBDataTList.Count(p => func(p));
return string.IsNullOrEmpty(errorString);
}
///
/// 查询指定条件的InfluxDB数据序列,使用外部委托参数时效率不高
///
/// InfluxDB数据类型
/// 指定条件的委托
/// InfluxDB数据序列
/// 错误字符串
/// 起始时间
/// 终止时间
/// 是否读取成功
public bool Read(out List influxDBDataTList, out string errorString, Func func = null, DateTime? startTime = null, DateTime? endTime = null)
where InfluxDBDataT : InfluxDBDataBase
{
//初始化
errorString = string.Empty;
influxDBDataTList = null;
//检查连接
if (!Connect(out string str))
{
errorString = str;
return false;
}
try
{
influxDBDataTList = InfluxDBQueryable.Queryable(DBName, Org, Client.GetQueryApiSync()).
Where(p => (startTime == null || p.Timestamp >= ((DateTime)startTime).ToUniversalTime()) &&
(endTime == null || p.Timestamp <= ((DateTime)endTime).ToUniversalTime())).ToList();
}
catch (Exception ex)
{
errorString = $"查询失败!{ex.Message}。\n";
return false;
}
if (func != null)
{
influxDBDataTList = influxDBDataTList.Where(p => func(p)).ToList();
}
return string.IsNullOrEmpty(errorString);
}
//
/// 查询指定条件的值序列和时间序列,使用外部委托参数时效率不高
///
/// InfluxDB数据类型
/// 指定条件的委托
/// 值序列
/// 时间序列
/// 错误字符串
/// 起始时间
/// 终止时间
/// 是否读取成功
public bool Read(out List valueList, out List timeList, out string errorString, Func func = null, DateTime? startTime = null, DateTime? endTime = null)
where InfluxDBDataT : InfluxDBDataBase
{
//初始化
errorString = string.Empty;
valueList = null;
timeList = null;
List influxDBDataTList = null;
Func newFunc = null;
if (func == null)
{
newFunc = new Func(p => p.Value.GetType() == typeof(ValueT));
}
else
{
newFunc = new Func(p => func.Invoke(p) && p.Value.GetType() == typeof(ValueT));
}
//检查连接
if (!Connect(out string str))
{
errorString = str;
return false;
}
if (Read(out influxDBDataTList, out errorString, newFunc, startTime, endTime))
{
valueList = influxDBDataTList.Select(p => (ValueT)p.Value).ToList();
timeList = influxDBDataTList.Select(p => p.Timestamp.ToLocalTime()).ToList();
}
return string.IsNullOrEmpty(errorString);
}
#endregion
#endregion
}
}