Skip to main content

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>net5.0</TargetFramework>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="TDengine.Connector" Version="3.0.*" 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 TDengineWS.Impl;

namespace Cloud.Examples
{
public class ConnectExample
{
static void Main(string[] args)
{
string dsn = Environment.GetEnvironmentVariable("TDENGINE_CLOUD_DSN");
Connect(dsn);
}

public static void Connect(string dsn)
{
// get connect
IntPtr conn = LibTaosWS.WSConnectWithDSN(dsn);
if (conn == IntPtr.Zero)
{
throw new Exception($"get connection failed,reason:{LibTaosWS.WSErrorStr(conn)},code:{LibTaosWS.WSErrorNo(conn)}");
}
else
{
Console.WriteLine("Establish connect success.");
}

// do something ...

// close connect
LibTaosWS.WSClose(conn);

}
}
}

查看源码

使用示例

基本插入和查询

<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="TDengine.Connector" Version="3.0.*" 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 TDengineDriver;
using TDengineWS.Impl;
using System.Collections.Generic;

namespace Cloud.Examples
{
public class UsageExample
{
static void Main(string[] args)
{
string dsn = Environment.GetEnvironmentVariable("TDENGINE_CLOUD_DSN");
IntPtr conn = Connect(dsn);
InsertData(conn);
SelectData(conn);
// close connect
LibTaosWS.WSClose(conn);
}

public static IntPtr Connect(string dsn)
{
// get connect
IntPtr conn = LibTaosWS.WSConnectWithDSN(dsn);
if (conn == IntPtr.Zero)
{
throw new Exception($"get connection failed,reason:{LibTaosWS.WSErrorStr(conn)},code:{LibTaosWS.WSErrorNo(conn)}");
}
return conn;
}


public static void InsertData(IntPtr conn)
{
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.meters TAGS('California.SanFrancisco', 1) VALUES ('2018-10-03 14:38:05.000', 10.30000, 219, 0.31000)" +
"test.d1002 USING test.meters TAGS('California.SanFrancisco', 2) VALUES ('2018-10-03 14:38:16.650', 10.30000, 218, 0.25000)" +
"test.d1003 USING test.meters TAGS('California.LosAngeles', 3) VALUES ('2018-10-03 14:38:05.500', 11.80000, 221, 0.28000)" +
"test.d1004 USING test.meters TAGS('California.LosAngeles', 4) VALUES ('2018-10-03 14:38:05.000', 10.80000, 223, 0.29000) ";

// create database under database named 'test'
IntPtr res = LibTaosWS.WSQuery(conn, createTable);
ValidQueryExecution(res);
// Free the query result every time when used up it.
LibTaosWS.WSFreeResult(res);

// insert data into the table created in previous step.
res = LibTaosWS.WSQuery(conn, insertData);
ValidQueryExecution(res);
// Free the query result every time when used up it.
LibTaosWS.WSFreeResult(res);
}
public static void SelectData(IntPtr conn)
{
string selectTable = "select * from test.meters";
IntPtr res = LibTaosWS.WSQueryTimeout(conn, selectTable,5000);
ValidQueryExecution(res);

// print meta
List<TDengineMeta> metas = LibTaosWS.WSGetFields(res);
foreach (var meta in metas)
{
Console.Write("{0} {1}({2})\t|", meta.name, meta.TypeName(), meta.size);
}
Console.WriteLine("");
List<object> dataSet = LibTaosWS.WSGetData(res);
for (int i = 0; i < dataSet.Count;)
{
for (int j = 0; j < metas.Count; j++)
{
Console.Write("{0}\t|\t", dataSet[i]);
i++;
}
Console.WriteLine("");
}
Console.WriteLine("");

// Free the query result every time when used up it.
LibTaosWS.WSFreeResult(res);
}

// Check if LibTaosWS.Query() execute correctly.
public static void ValidQueryExecution(IntPtr res)
{
int code = LibTaosWS.WSErrorNo(res);
if (code != 0)
{
throw new Exception($"execute SQL failed: reason: {LibTaosWS.WSErrorStr(res)}, code:{code}");
}
}
}
}

查看源码

STMT 插入

<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5</TargetFramework>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="TDengine.Connector" Version="3.0.*" 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 TDengineWS.Impl;
using TDengineDriver;
using System.Runtime.InteropServices;

namespace Cloud.Examples
{
public class STMTExample
{
static void Main(string[] args)
{
string dsn = Environment.GetEnvironmentVariable("TDENGINE_CLOUD_DSN");
IntPtr conn = Connect(dsn);
// assume table has been created.
// CREATE STABLE if not exists test.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)
string insert = "insert into ? using test.meters tags(?,?) values(?,?,?,?)";

// Init STMT
IntPtr stmt = LibTaosWS.WSStmtInit(conn);

if (stmt != IntPtr.Zero)
{
// Prepare SQL
int code = LibTaosWS.WSStmtPrepare(stmt, insert);
ValidSTMTStep(code, stmt, "WSInit()");

// Bind child table name and tags
TAOS_MULTI_BIND[] tags = new TAOS_MULTI_BIND[2] { WSMultiBind.WSBindBinary(new string[] { "California.LosAngeles" }), WSMultiBind.WSBindInt(new int?[] { 6 }) };
code = LibTaosWS.WSStmtSetTbnameTags(stmt, "test.d1005",tags, 2);
ValidSTMTStep(code, stmt, "WSStmtSetTbnameTags()");

// bind column value
TAOS_MULTI_BIND[] data = new TAOS_MULTI_BIND[4];
data[0] = WSMultiBind.WSBindTimestamp(new long[] { 1538551000000, 1538552000000, 1538553000000, 1538554000000, 1538555000000 });
data[1] = WSMultiBind.WSBindFloat(new float?[] { 10.30000F, 10.30000F, 11.30000F, 10.30000F, 10.80000F });
data[2] = WSMultiBind.WSBindInt(new int?[] { 218, 219, 221, 222, 223 });
data[3] = WSMultiBind.WSBindFloat(new float?[] { 0.28000F, 0.29000F, 0.30000F, 0.31000F, 0.32000F });
code = LibTaosWS.WSStmtBindParamBatch(stmt, data, 4);
ValidSTMTStep(code, stmt, "WSStmtBindParamBatch");

LibTaosWS.WSStmtAddBatch(stmt);
ValidSTMTStep(code, stmt, "WSStmtAddBatch");

IntPtr affectRowPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Int32)));
LibTaosWS.WSStmtExecute(stmt, affectRowPtr);
ValidSTMTStep(code, stmt, "WSStmtExecute");
Console.WriteLine("STMT affect rows:{0}", Marshal.ReadInt32(affectRowPtr));

LibTaosWS.WSStmtClose(stmt);

// Free allocated memory
Marshal.FreeHGlobal(affectRowPtr);
WSMultiBind.WSFreeTaosBind(tags);
WSMultiBind.WSFreeTaosBind(data);
}
// close connect
LibTaosWS.WSClose(conn);
}

public static IntPtr Connect(string dsn)
{
// get connect
IntPtr conn = LibTaosWS.WSConnectWithDSN(dsn);
if (conn == IntPtr.Zero)
{
throw new Exception($"get connection failed,reason:{LibTaosWS.WSErrorStr(conn)},code:{LibTaosWS.WSErrorNo(conn)}");
}
return conn;
}

public static void ValidSTMTStep(int code, IntPtr wsStmt, string method)
{
if (code != 0)
{
throw new Exception($"{method} failed,reason: {LibTaosWS.WSErrorStr(wsStmt)}, code: {code}");
}
else
{
Console.WriteLine("{0} success", method);
}
}
}
}

查看源码

重要更新记录

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 提供,具体请参考:

常见问题

  1. "Unable to establish connection","Unable to resolve FQDN"

一般是因为 FQDN 配置不正确。可以参考如何彻底搞懂 TDengine 的 FQDN解决。

  1. 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 即可。

API 参考

API 参考