使用 C# 连接器建立连接
创建项目
dotnet new console -o example
Add C# TDengine Driver class lib
cd example
vim example.csproj
增加下面的 ItemGroup 和 Task 配置到您的工程文件中。
<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>
dotnet add package TDengine.Connector
配置
在您的终端里面执行下面的命令设置 TDengine Cloud 的网关地址和令牌为环境变量。
- Bash
- CMD
- Powershell
export TDENGINE_CLOUD_ENDPOINT="<cloud_endpoint>"
export TDENGINE_CLOUD_TOKEN="<cloud_token>"
set TDENGINE_CLOUD_ENDPOINT=<cloud_endpoint>
set TDENGINE_CLOUD_TOKEN=<cloud_token>
$env:TDENGINE_CLOUD_ENDPOINT='<cloud_endpoint>'
$env:TDENGINE_CLOUD_TOKEN='<cloud_token>'
IMPORTANT
替换 <cloud_endpoint>
和 <cloud_token>
为 TDengine Cloud 的网关地址和令牌。
获取 TDengine Cloud 的网关地址和令牌,可以登录TDengine Cloud 后点击左边的”编程“菜单,然后选择”C#“。
建立连接
<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;
}
}
}
}
客户端连接建立连接以后,想了解更多写入数据和查询数据的内容,请参考 写入 和 查询。
想知道更多通过 REST 接口写入数据的详情,请参考REST 接口。