docs/en/14-reference/05-connector/40-csharp.md
import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; import RequestId from "../../assets/resources/_request_id.mdx";
TDengine.Connector is the C# language connector provided by TDengine. C# developers can use it to develop C# applications that access data in the TDengine cluster.
| Connector Version | Major Changes | TDengine Version |
|---|---|---|
| 3.1.10 | Support TDengine TSDB Token authentication. | - |
| 3.1.9 | The external interface of stmt remains unchanged; the internal implementation has been refactored into stmt2. | - |
| 3.1.8 | Support connection-level timezone settings and strictly validate the binding types of statements against database types. | - |
| 3.1.7 | Support IPv6 connections and DECIMAL data type. | 3.3.6.0 and higher |
| 3.1.6 | Optimize WebSocket connection message handling. | - |
| 3.1.5 | Fix WebSocket encoding error for Chinese character length. | - |
| 3.1.4 | Improved WebSocket query and insert performance. | 3.3.2.0 and higher |
| 3.1.3 | Supported WebSocket auto-reconnect. | - |
| 3.1.2 | Fixed schemaless resource release. | - |
| 3.1.1 | Supported varbinary and geometry types. | - |
| 3.1.0 | WebSocket uses a native C# implementation. | 3.2.1.0 and higher |
TDengine.Connector will throw exceptions, and applications need to handle these exceptions. The taosc exception type TDengineError includes an error code and error message, which applications can use to handle the error.
For error reporting in other TDengine modules, please refer to Error Codes
For error code information please refer to Error Codes
| TDengine DataType | C# Type |
|---|---|
| TIMESTAMP | DateTime |
| TINYINT | sbyte |
| SMALLINT | short |
| INT | int |
| BIGINT | long |
| TINYINT UNSIGNED | byte |
| SMALLINT UNSIGNED | ushort |
| INT UNSIGNED | uint |
| BIGINT UNSIGNED | ulong |
| FLOAT | float |
| DOUBLE | double |
| BOOL | bool |
| BINARY | byte[] |
| NCHAR | string |
| JSON | byte[] |
| VARBINARY | byte[] |
| GEOMETRY | byte[] |
| DECIMAL | decimal |
Note:
decimal type, which supports high-precision decimal numbers.
Since C#'s decimal type differs from TDengine's DECIMAL type in precision and range,
the C#'s decimal has a maximum precision of 29 digits, while TDengine's DECIMAL type supports up to 38 digits of precision.
The following should be noted when using it:
decimal type, you can use GetDecimal or GetValue to retrieve it.decimal type, the GetDecimal and GetValue methods will throw an OverflowException.
In such cases, you can use the GetString method to obtain the string representation.For the source code of the example programs, please refer to: Example Programs
The TDengine.Data.Client interface implements the ADO.NET driver, supporting connections to the TDengine database for data operations.
ConnectionStringBuilder uses a key-value pair method to set connection parameters, where the key is the parameter name and the value is the parameter value, separated by semicolons ;.
For example:
"protocol=WebSocket;host=127.0.0.1;port=6041;useSSL=false"
For example: "host=127.0.0.1;port=6030;username=root;password=taosdata;protocol=Native;db=test"
Supported parameters include:
host: Address of the TDengine instance.port: Port of the TDengine instance.username: Username for the connection.password: Password for the connection.protocol: Connection protocol, options are Native or WebSocket, default is Native.db: Database to connect to.timezone: The timezone used for parsing time types in the query result set. Defaults to the local timezone. For format details, see Timezone Settings.connectionTimezone: Connection-level timezone setting (supported in version 3.1.8 and above), only available for .NET 6+ and supports IANA timezone format exclusively. Cannot be set simultaneously with timezone. For details, see Timezone Settings.bearerToken: Token for connecting to TDengine TSDB (supported in version 3.1.10 and above).For example: "protocol=WebSocket;host=127.0.0.1;port=6041;useSSL=false;enableCompression=true;autoReconnect=true;reconnectIntervalMs=10;reconnectRetryCount=5"
Supported parameters include:
host: Address of the TDengine instance.port: Port of the TDengine instance.username: Username for the connection.password: Password for the connection.protocol: Connection protocol, options are Native or WebSocket, default is Native.db: Database to connect to.timezone: The timezone used for parsing time types in the query result set. Defaults to the local timezone. For format details, see Timezone Settings.connectionTimezone: Connection-level timezone setting (supported in version 3.1.8 and above), only available for .NET 6+ and supports IANA timezone format exclusively. Cannot be set simultaneously with timezone. For details, see Timezone Settings.connTimeout: Connection timeout, default is 1 minute.readTimeout: Read timeout, default is 5 minutes.writeTimeout: Send timeout, default is 10 seconds.token: Token for connecting to TDengine cloud.useSSL: Whether to use SSL connection, default is false.enableCompression: Whether to enable WebSocket compression, default is false.autoReconnect: Whether to automatically reconnect, default is false.reconnectRetryCount: Number of retries for reconnection, default is 3.reconnectIntervalMs: Interval for reconnection in milliseconds, default is 2000.bearerToken: Token for connecting to TDengine TSDB (supported in version 3.1.10 and above).Starting from version 3.1.8, the C# driver supports connection-level timezone settings. You can specify the connection-level timezone by setting the connectionTimezone parameter.
America/New_Yorktimezone parameterThis parameter affects the time type resolution for all queries and write operations executed through this connection, as well as the time type resolution of query result sets.
When the TDengine server is in UTC timezone and connectionTimezone=America/New_York is set:
Execute the write SQL:
insert into db.tb values('2025-08-08 14:00:00',1)
2025-08-08 14:00:00 in New York timezone2025-08-08 18:00:00.000 (UTC time)When executing query SQL select * from db.tb with connectionTimezone=America/New_York, the time types in the query result set will be parsed as New York timezone.
| Method | Return Type | Example Output | Remarks |
|---|---|---|---|
GetValue | DateTime | 2025-08-08 14:00:00.000 | Represents New York timezone time |
GetDateTime | DateTime | 2025-08-08 14:00:00.000 | Same behavior as GetValue |
GetDateTimeOffset | DateTimeOffset | 2025-08-08 14:00:00.000 (yyyy-MM-dd HH:mm:ss.fff) or 2025-08-08 14:00:00.000-04:00 (yyyy-MM-dd HH:mm:ss.fffK) | New method added in 3.1.8 |
GetInt64 | long | 1754676000000 (millisecond precision) | Time precision matches database definition (3.1.8 supports returning timestamps via GetInt64) |
The timezone parameter sets the timezone used for parsing time types in query result sets, internally using the TimeZoneInfo.FindSystemTimeZoneById method to obtain timezone information:
FindSystemTimeZoneById attempts to match subkey names under the registry branch HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Time Zones.For example, for New York timezone:
Eastern Standard TimeAmerica/New_YorkFor .NET 6.0 and above, you can uniformly use IANA timezone formats, e.g., America/New_York.
Unspecified. Using the ToUniversalTime() method will treat it as local timezone to get UTC time, resulting in incorrect UTC time. Therefore, all DateTime objects with Kind property as Unspecified are prohibited for parameter binding.TIMESTAMP type, converting to timestamp using UtcTicks for writing.TIMESTAMP type, with time precision needing to match the database.The ConnectionStringBuilder class provides functionality for parsing connection configuration strings.
public ConnectionStringBuilder(string connectionString)
connectionString: Connection configuration string.The C# driver supports creating ADO.NET connections, returning objects that support the ADO.NET standard DbConnection interface, and also provides the ITDengineClient interface, which extends some schema-less write interfaces.
The standard interfaces supported by ADO.NET connections are as follows:
public TDengineConnection(string connectionString)
connectionString: Connection configuration string.ArgumentException if the format is incorrect.public void ChangeDatabase(string databaseName)
databaseName: Database name.TDengineError exception if execution fails.public void Close()
public void Open()
TDengineError exception if opening fails, be aware of potential network issues with WebSocket connections.public string ServerVersion
TDengineError exception if execution fails.public string DataSource
public string Database
public TDengineCommand(TDengineConnection connection)
connection: TDengineConnection object.TDengineError exception if execution fails.public void Prepare()
InvalidOperationException if open has not been executed or CommandText is not set.public string CommandText
public new virtual TDengineParameterCollection Parameters
public static ITDengineClient Open(ConnectionStringBuilder builder)
builder: Connection configuration.TDengineError exception if opening fails, be aware of potential network issues with WebSocket connections.void SchemalessInsert(string[] lines, TDengineSchemalessProtocol protocol,TDengineSchemalessPrecision precision, int ttl, long reqId)
lines: Array of data lines.protocol: Data protocol, supported protocols: TSDB_SML_LINE_PROTOCOL = 1 TSDB_SML_TELNET_PROTOCOL = 2 TSDB_SML_JSON_PROTOCOL = 3.precision: Time precision, supported configurations: TSDB_SML_TIMESTAMP_NOT_CONFIGURED = 0 TSDB_SML_TIMESTAMP_HOURS = 1 TSDB_SML_TIMESTAMP_MINUTES = 2 TSDB_SML_TIMESTAMP_SECONDS = 3 TSDB_SML_TIMESTAMP_MILLI_SECONDS = 4 TSDB_SML_TIMESTAMP_MICRO_SECONDS = 5 TSDB_SML_TIMESTAMP_NANO_SECONDS = 6.ttl: Data expiration time, 0 means not configured.reqId: Request ID.TDengineError exception if execution fails.The C# driver provides a DbCommand interface that complies with the ADO.NET standard, supporting the following features:
SELECT statements).INSERT, UPDATE, DELETE, etc.ResultSet object) returned after query execution and iterate through the returned data.Additionally, the C# driver also provides an extended interface for request link tracking.
public int ExecuteNonQuery()
TDengineError exception on execution failure.public object ExecuteScalar()
TDengineError exception on execution failure.public DbDataReader ExecuteReader()
TDengineError exception on execution failure.public void Dispose();
The extended interface is mainly used for request link tracking.
IRows Query(string query, long reqId)
query: Query statement.reqId: Request ID.TDengineError exception on execution failure.long Exec(string query, long reqId)
query: SQL statement.reqId: Request ID.TDengineError exception on execution failure.The C# driver provides a DbDataReader interface that complies with the ADO.NET standard, offering methods to read metadata and data from the result set.
The DbDataReader interface provides the following methods to retrieve the result set:
public bool GetBoolean(int ordinal)
ordinal: Column index.InvalidCastException exception if types do not match.public byte GetByte(int ordinal)
ordinal: Column index.InvalidCastException exception if types do not match.public long GetBytes(int ordinal, long dataOffset, byte[] buffer, int bufferOffset, int length)
ordinal: Column index.dataOffset: Data offset.buffer: Buffer.bufferOffset: Buffer offset.length: Length.InvalidCastException exception if types do not match.public char GetChar(int ordinal)
ordinal: Column index.InvalidCastException if the type does not correspond.public long GetChars(int ordinal, long dataOffset, char[] buffer, int bufferOffset, int length)
ordinal: Column index.dataOffset: Data offset.buffer: Buffer.bufferOffset: Buffer offset.length: Length.InvalidCastException if the type does not correspond.public DateTime GetDateTime(int ordinal)
ordinal: Column index.InvalidCastException if the type does not correspond.public decimal GetDecimal(int ordinal)
ordinal: Column index.InvalidCastException if the type does not correspond.OverflowException if the value exceeds the range of C#'s decimal type.public double GetDouble(int ordinal)
ordinal: Column index.InvalidCastException if the type does not correspond.public float GetFloat(int ordinal)
ordinal: Column index.InvalidCastException if the type does not correspond.public short GetInt16(int ordinal)
ordinal: Column index.InvalidCastException if the type does not correspond.public int GetInt32(int ordinal)
ordinal: Column index.InvalidCastException if the type does not correspond.public long GetInt64(int ordinal)
ordinal: Column index.InvalidCastException if the type does not correspond.public string GetString(int ordinal)
ordinal: Column index.InvalidCastException if the type does not correspond.public object GetValue(int ordinal)
ordinal: Column index.public int GetValues(object[] values)
values: Array of values.public bool IsDBNull(int ordinal)
ordinal: Column index.public int RecordsAffected
public bool HasRows
public bool Read()
public IEnumerator GetEnumerator()
public void Close()
The DbDataReader interface provides the following methods to obtain result set metadata:
public DataTable GetSchemaTable()
public string GetDataTypeName(int ordinal)
ordinal: Column index.public Type GetFieldType(int ordinal)
ordinal: Column index.public string GetName(int ordinal)
ordinal: Column index.public int GetFieldSize(int ordinal)
ordinal: Column index.public int GetOrdinal(string name)
name: Column name.public int FieldCount
The TDengineCommand class supports parameter binding.
The TDengineCommand class inherits the DbCommand interface, supporting the following features:
public string CommandText
public new virtual TDengineParameterCollection Parameters
TDengineParameterCollection object.The TDengineParameterCollection inherits the DbParameterCollection interface, supporting the following features:
public int Add(object value)
value: Parameter value.public void Clear()
public bool Contains(object value)
value: Parameter value.public int IndexOf(object value)
value: Parameter value.public void Insert(int index, object value)
index: Index.value: Parameter value.public void Remove(object value)
value: Parameter value.public void RemoveAt(int index)
index: Index.public void RemoveAt(string parameterName)
parameterName: Parameter name.public int Count
public int IndexOf(string parameterName)
parameterName: Parameter name.public bool Contains(string value)
value: Parameter name.public void CopyTo(Array array, int index)
array: Target array.index: Index.public IEnumerator GetEnumerator()
public void AddRange(Array values)
values: Array of parameters.TDengineParameter inherits from the DbParameter interface, supporting the following functionalities:
public TDengineParameter(string name, object value)
name: Parameter name, must start with @, such as @0, @1, @2, etc.value: Parameter value, must correspond one-to-one with C# column types and TDengine column types.public string ParameterName
public object Value
ITDengineClient interface provides an extended parameter binding interface.
IStmt StmtInit(long reqId)
reqId: Request ID.TDengineError exception on failure.IStmt interface provides an extended parameter binding interface.
void Prepare(string query)
query: Query statement.TDengineError exception on failure.bool IsInsert()
TDengineError exception on execution failure.void SetTableName(string tableName)
tableName: Table name.TDengineError exception on execution failure.void SetTags(object[] tags)
tags: Array of tags.TDengineError exception on execution failure.TaosFieldE[] GetTagFields()
TDengineError exception on execution failure.TaosFieldE[] GetColFields()
TDengineError exception on execution failure.void BindRow(object[] row)
row: Array of row data.TDengineError exception on execution failure.void BindColumn(TaosFieldE[] fields, params Array[] arrays)
fields: Array of field attributes.arrays: Arrays of multiple column data.TDengineError exception on execution failure.void AddBatch()
TDengineError exception on execution failure.void Exec()
TDengineError exception on execution failure.long Affected()
TDengineError exception on execution failure.IRows Result()
TDengineError exception on execution failure.The ConsumerBuilder class provides interfaces related to consumer building, the ConsumeResult class provides interfaces related to consumption results, and the TopicPartitionOffset class provides interfaces related to partition offsets. ReferenceDeserializer and DictionaryDeserializer provide support for deserialization.
public ConsumerBuilder(IEnumerable<KeyValuePair<string, string>> config)
config: Consumption configuration.Supported properties for creating consumers:
useSSL: Whether to use SSL connection, default is false.token: Token for connecting to TDengine cloud.ws.message.enableCompression: Whether to enable WebSocket compression, default is false.ws.autoReconnect: Whether to automatically reconnect, default is false.ws.reconnect.retry.count: Number of reconnection attempts, default is 3.ws.reconnect.interval.ms: Reconnection interval in milliseconds, default is 2000.connectionTimezone: Connection-level timezone setting (supported in version 3.1.8 and above, currently only for timezone functionality when parsing result sets). Only available for .NET 6+ and supports IANA timezone format exclusively. For details, see Timezone Settings.For other parameters, please refer to: Consumer Parameter List, note that the default value of auto.offset.reset in message subscription has changed starting from TDengine server version 3.2.0.0.
public IConsumer<TValue> Build()
IConsumer interface provides the following consumer-related APIs:
ConsumeResult<TValue> Consume(int millisecondsTimeout)
millisecondsTimeout: Timeout in milliseconds.TDengineError exception on failure.List<TopicPartition> Assignment { get; }
TDengineError exception on failure.List<string> Subscription()
TDengineError exception on failure.void Subscribe(IEnumerable<string> topic)
topic: List of topics.TDengineError exception on failure.void Subscribe(string topic)
topic: Topic.TDengineError exception on failure.void Unsubscribe()
TDengineError exception on failure.void Commit(ConsumeResult<TValue> consumerResult)
consumerResult: Consumption result.TDengineError exception on failure.List<TopicPartitionOffset> Commit()
TDengineError exception on failure.void Commit(IEnumerable<TopicPartitionOffset> offsets)
offsets: Partition offsets.TDengineError exception on failure.void Seek(TopicPartitionOffset tpo)
tpo: Partition offset.TDengineError exception on failure.List<TopicPartitionOffset> Committed(TimeSpan timeout)
timeout: Timeout (unused).TDengineError exception on failure.List<TopicPartitionOffset> Committed(IEnumerable<TopicPartition> partitions, TimeSpan timeout)
partitions: List of partitions.timeout: Timeout (unused).TDengineError exception on failure.Offset Position(TopicPartition partition)
partition: Partition.TDengineError exception if execution fails.void Close()
ConsumeResult class provides interfaces related to consumption results:
public List<TmqMessage<TValue>> Message
TmqMessage class provides the specific content of messages:
public class TmqMessage<TValue>
{
public string TableName { get; set; }
public TValue Value { get; set; }
}
TableName: Table nameValue: Message contentGet TopicPartitionOffset from ConsumeResult:
public TopicPartitionOffset TopicPartitionOffset
TopicPartitionOffset class provides interfaces for getting partition information:
public string Topic { get; }
public Partition Partition { get; }
public Offset Offset { get; }
public TopicPartition TopicPartition
public string ToString()
Offset class provides interfaces related to offset:
public long Value
The C# driver provides two deserialization classes: ReferenceDeserializer and DictionaryDeserializer. Both implement the IDeserializer interface.
ReferenceDeserializer is used to deserialize a consumed record into an object, ensuring that the object class's property names correspond to the consumed data's column names and that the types match.
DictionaryDeserializer will deserialize a consumed row of data into a Dictionary<string, object> object, where the key is the column name and the value is the object.
Interfaces of ReferenceDeserializer and DictionaryDeserializer are not directly called by users, please refer to the usage examples.