Skip to main content

TDengine C# Client Library

TDengine.Connector is the official C# client library for TDengine. C# developers can develop applications to access TDengine instance data.

This article describes how to install TDengine.Connector in a Linux or Windows environment and connect to TDengine clusters via TDengine.Connector to perform basic operations such as data writing and querying.

The source code for TDengine.Connector is hosted on GitHub.

Version support

Please refer to version support list

Installation

Pre-installation

Add TDengine.Connector through Nuget

dotnet add package TDengine.Connector

Establishing a connection

<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>

view source code

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;
}
}
}
}

view source code

Usage examples

Basic Insert and Query

<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>

view source code

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}");
}
}
}
}
}

view source code

STMT Insert

<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>

view source code

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;
}
}
}
}

view source code

Important Updates

TDengine.ConnectorDescription
3.0.2Support .NET Framework 4.5 and above. Support .Net standard 2.0. Nuget package includes dynamic library for WebSocket.
3.0.1Support WebSocket and Cloud,With function query, insert, and parameter binding
3.0.0Supports TDengine 3.0.0.0. TDengine 2.x is not supported. Added TDengine.Impl.GetData() interface to deserialize query results.
1.0.7Fixed TDengine.Query() memory leak.
1.0.6Fix schemaless bug in 1.0.4 and 1.0.5.
1.0.5Fix Windows sync query Chinese error bug.
1.0.4Add asynchronous query, subscription, and other functions. Fix the binding parameter bug.
1.0.3Add parameter binding, schemaless, JSON tag, etc.
1.0.2Add connection management, synchronous query, error messages, etc.

Other descriptions

Third-party driver

Taos is an ADO.NET client library for TDengine, supporting Linux and Windows platforms. Community contributor Maikebing@@maikebing contributes the library. Please refer to:

Frequently Asked Questions

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

    Usually, it's caused by an incorrect FQDN configuration. Please refer to this section in the FAQ to troubleshoot.

  2. Unhandled exception. System.DllNotFoundException: Unable to load DLL 'taos' or one of its dependencies: The specified module cannot be found.

    This is usually because the program did not find the dependent client driver. The solution is to copy C:\TDengine\driver\taos.dll to the C:\Windows\System32\ directory on Windows, and create the following soft link on Linux ln -s /usr/local/taos/driver/libtaos.so.x.x .x.x /usr/lib/libtaos.so will work.

API Reference

API Reference