C# Connector
TDengine.Connector
是 TDengine 提供的 C# 语言连接器。C# 开发人员可以通过它开发存取 TDengine 集群数据的 C# 应 用软件。
本文介绍如何在 Linux 或 Windows 环境中安装 TDengine.Connector
,并通过 TDengine.Connector
连接 TDengine 集群,进行数据写入、查询等基本操作。
TDengine.Connector
的源码托管在 GitHub。
版本支持
请参考版本支持列表
安装步骤
安装前准备
安装 TDengine.Connector
通过 Nuget 增加TDengine.Connector
包
dotnet add package TDengine.Connector
建立连接
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="TDengine.Connector" Version="3.1.*" GeneratePathProperty="true" />
</ItemGroup>
<Target Name="copyDLLDependency" BeforeTargets="BeforeBuild">
<ItemGroup>
<DepDLLFiles Include="$(PkgTDengine_Connector)\runtimes\**\*.*" />
</ItemGroup>
<Copy SourceFiles="@(DepDLLFiles)" DestinationFolder="$(OutDir)" />
</Target>
</Project>
using System;
using System.Text;
using TDengine.Driver;
using TDengine.Driver.Client;
namespace Cloud.Examples
{
public class ConnectExample
{
static void Main(string[] args)
{
var cloudEndPoint = Environment.GetEnvironmentVariable("TDENGINE_CLOUD_ENDPOINT");
var cloudToken = Environment.GetEnvironmentVariable("TDENGINE_CLOUD_TOKEN");
var connectionString = $"protocol=WebSocket;host={cloudEndPoint};port=443;useSSL=true;token={cloudToken};";
// Connect to TDengine server using WebSocket
var builder = new ConnectionStringBuilder(connectionString);
try
{
// Open connection with using block, it will close the connection automatically
using (var client = DbDriver.Open(builder))
{
Console.WriteLine("Connected to " + builder.ToString() + " successfully.");
}
}
catch (TDengineError e)
{
// handle TDengine error
Console.WriteLine("Failed to connect to " + builder.ToString() + "; ErrCode:" + e.Code +
"; ErrMessage: " + e.Error);
throw;
}
catch (Exception e)
{
// handle other exceptions
Console.WriteLine("Failed to connect to " + builder.ToString() + "; Err:" + e.Message);
throw;
}
}
}
}
使用示例
基本插入和查询
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="TDengine.Connector" Version="3.1.*" GeneratePathProperty="true" />
</ItemGroup>
<Target Name="copyDLLDependency" BeforeTargets="BeforeBuild">
<ItemGroup>
<DepDLLFiles Include="$(PkgTDengine_Connector)\runtimes\**\*.*" />
</ItemGroup>
<Copy SourceFiles="@(DepDLLFiles)" DestinationFolder="$(OutDir)" />
</Target>
</Project>
using System;
using System.Text;
using TDengine.Driver;
using TDengine.Driver.Client;
namespace Cloud.Examples
{
public class UsageExample
{
static void Main(string[] args)
{
var cloudEndPoint = Environment.GetEnvironmentVariable("TDENGINE_CLOUD_ENDPOINT");
var cloudToken = Environment.GetEnvironmentVariable("TDENGINE_CLOUD_TOKEN");
var connectionString = $"protocol=WebSocket;host={cloudEndPoint};port=443;useSSL=true;token={cloudToken};";
// Connect to TDengine server using WebSocket
var builder = new ConnectionStringBuilder(connectionString);
try
{
// Open connection with using block, it will close the connection automatically
using (var client = DbDriver.Open(builder))
{
InsertData(client);
SelectData(client);
}
}catch (TDengineError e)
{
// handle TDengine error
Console.WriteLine(e.Message);
throw;
}
catch (Exception e)
{
// handle other exceptions
Console.WriteLine(e.Message);
throw;
}
}
public static void InsertData(ITDengineClient client)
{
string createTable = "CREATE STABLE if not exists test.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)";
string insertData = "INSERT INTO " +
"test.d1001 USING test.meters1 TAGS('California.SanFrancisco', 1) VALUES ('2018-10-03 14:38:05.000', 10.30000, 219, 0.31000)" +
"test.d1002 USING test.meters1 TAGS('California.SanFrancisco', 2) VALUES ('2018-10-03 14:38:16.650', 10.30000, 218, 0.25000)" +
"test.d1003 USING test.meters1 TAGS('California.LosAngeles', 3) VALUES ('2018-10-03 14:38:05.500', 11.80000, 221, 0.28000)" +
"test.d1004 USING test.meters1 TAGS('California.LosAngeles', 4) VALUES ('2018-10-03 14:38:05.000', 10.80000, 223, 0.29000) ";
// create stable under database named 'test'
var affected = client.Exec(createTable);
Console.WriteLine($"Create stable meters, affected rows: {affected}");
// insert data into the table created in previous step.
affected = client.Exec(insertData);
Console.WriteLine("insert " + affected + " rows to test.meters successfully.");
}
public static void SelectData(ITDengineClient client)
{
string selectTable = "select * from test.meters";
using (var rows = client.Query(selectTable))
{
while (rows.Read())
{
var ts = (DateTime)rows.GetValue(0);
var current = (float)rows.GetValue(1);
var voltage = (int)rows.GetValue(2);
var phase = (float)rows.GetValue(3);
var location = Encoding.UTF8.GetString((byte[])rows.GetValue(4));
Console.WriteLine(
$"ts: {ts:yyyy-MM-dd HH:mm:ss.fff}, current: {current}, voltage: {voltage}, phase: {phase}, location: {location}");
}
}
}
}
}
STMT 插入
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="TDengine.Connector" Version="3.1.*" GeneratePathProperty="true" />
</ItemGroup>
<Target Name="copyDLLDependency" BeforeTargets="BeforeBuild">
<ItemGroup>
<DepDLLFiles Include="$(PkgTDengine_Connector)\runtimes\**\*.*" />
</ItemGroup>
<Copy SourceFiles="@(DepDLLFiles)" DestinationFolder="$(OutDir)" />
</Target>
</Project>
using System;
using System.Text;
using TDengine.Driver;
using TDengine.Driver.Client;
namespace Cloud.Examples
{
public class STMTExample
{
static void Main(string[] args)
{
var numOfSubTable = 10;
var numOfRow = 10;
var random = new Random();
var cloudEndPoint = Environment.GetEnvironmentVariable("TDENGINE_CLOUD_ENDPOINT");
var cloudToken = Environment.GetEnvironmentVariable("TDENGINE_CLOUD_TOKEN");
var connectionString = $"protocol=WebSocket;host={cloudEndPoint};port=443;useSSL=true;token={cloudToken};";
// Connect to TDengine server using WebSocket
var builder = new ConnectionStringBuilder(connectionString);
try
{
// Open connection with using block, it will close the connection automatically
using (var client = DbDriver.Open(builder))
{
// use database
client.Exec("USE test");
// assume table has been created.
using (var stmt = client.StmtInit())
{
String sql = "INSERT INTO ? USING meters TAGS(?,?) VALUES (?,?,?,?)";
stmt.Prepare(sql);
for (int i = 1; i <= numOfSubTable; i++)
{
var tableName = $"d_bind_{i}";
// set table name
stmt.SetTableName(tableName);
// set tags
stmt.SetTags(new object[] { i, $"location_{i}" });
var current = DateTime.Now;
// bind rows
for (int j = 0; j < numOfRow; j++)
{
stmt.BindRow(new object[]
{
current.Add(TimeSpan.FromMilliseconds(j)),
random.NextSingle() * 30,
random.Next(300),
random.NextSingle()
});
}
// add batch
stmt.AddBatch();
// execute
stmt.Exec();
// get affected rows
var affectedRows = stmt.Affected();
Console.WriteLine($"Successfully inserted {affectedRows} rows to {tableName}.");
}
}
}
}
catch (TDengineError e)
{
// handle TDengine error
Console.WriteLine("Failed to insert to table meters using stmt, ErrCode: " + e.Code + ", ErrMessage: " + e.Error);
throw;
}
catch (Exception e)
{
// handle other exceptions
Console.WriteLine("Failed to insert to table meters using stmt, ErrMessage: " + e.Message);
throw;
}
}
}
}
重要更新记录
TDengine.Connector | 说明 |
---|---|
3.0.2 | 支持 .NET Framework 4.5 及以上,支持 .NET standard 2.0。Nuget Package 包含 WebSocket 动态库。 |
3.0.1 | 支持 WebSocket 和 Cloud,查询,插入,参数绑定。 |
3.0.0 | 支持 TDengine 3.0.0.0,不兼容 2.x。新增接口TDengine.Impl.GetData(),解析查询结果。 |
1.0.7 | 修复 TDengine.Query()内存泄露。 |
1.0.6 | 修复 schemaless 在 1.0.4 和 1.0.5 中失效 bug。 |
1.0.5 | 修复 Windows 同步查询中文报错 bug。 |
1.0.4 | 新增异步查询,订阅等功能。修复绑定参数 bug。 |
1.0.3 | 新增参数绑定、schemaless、 json tag等功能。 |
1.0.2 | 新增连接管理、同步查询、错误信息等功能。 |
其他说明
第三方驱动
IoTSharp.Data.Taos
是一个 TDengine 的 ADO.NET 连接器,其中包含了用于EntityFrameworkCore 的提供程序 IoTSharp.EntityFrameworkCore.Taos 和健康检查组件 IoTSharp.HealthChecks.Taos ,支持 Linux,Windows 平台。该连接器由社区贡献者麦壳饼@@maikebing
提供,具体请参考:
- 接口下载: <https://github.com/IoTSharp/EntityFrameworkCore.Taos>
- 用法说明: <https://www.taosdata.com/blog/2020/11/02/1901.html>
常见问题
- "Unable to establish connection","Unable to resolve FQDN"
一般是因为 FQDN 配置不正确。可以参考如何彻底搞懂 TDengine 的 FQDN解决。
- Unhandled exception. System.DllNotFoundException: Unable to load DLL 'taos' or one of its dependencies: 找不到指定的模块。
一般是因为程序没有找到依赖的客户端驱动。解决方法为:Windows 下可以将 C:\TDengine\driver\taos.dll
拷贝到 C:\Windows\System32\
目录下,Linux 下建立如下软链接 ln -s /usr/local/taos/driver/libtaos.so.x.x.x.x /usr/lib/libtaos.so
即可。