Connect to TDengine

Any application running on any platform can access TDengine through the REST API provided by TDengine. For information, see REST API. Applications can also use the connectors for various programming languages, including C/C++, Java, Python, Go, Node.js, C#, and Rust, to access TDengine. These connectors support connecting to TDengine clusters using both native interfaces (taosc). Some connectors also support connecting over a REST interface. Community developers have also contributed several unofficial connectors, such as the ADO.NET connector, the Lua connector, and the PHP connector.

Establish Connection

There are two ways for a connector to establish connections to TDengine:

  1. REST connection through the REST API provided by the taosAdapter component.
  2. Native connection through the TDengine client driver (taosc).

For REST and native connections, connectors provide similar APIs for performing operations and running SQL statements on your databases. The main difference is the method of establishing the connection, which is not visible to users.

Key differences:

  1. The REST connection is more accessible with cross-platform support, however it results in a 30% performance downgrade.
  2. The TDengine client driver (taosc) has the highest performance with all the features of TDengine like Parameter Binding, Subscription, etc.

Install Client Driver taosc

If you are choosing to use the native connection and the the application is not on the same host as TDengine server, the TDengine client driver taosc needs to be installed on the application host. If choosing to use the REST connection or the application is on the same host as TDengine server, this step can be skipped. It’s better to use same version of taosc as the TDengine server.

Install

  • Linux
  • Windows
  • MacOS
  1. Download the client installation package

    Download TDengine

    TDengine Database

    Enter your email to receive a download link

    I would like to receive TDengine news and communications at this address.

    Submit

    Close

    All Downloads

  2. Unzip

    Download the package to any directory the current user has read/write permission. Then execute tar -xzvf TDengine-client-VERSION.tar.gz command. The VERSION should be the version of the package you just downloaded.

  3. Execute the install script

    Once the package is unzipped, you will see the following files in the directory:

    • install_client.sh: install script
    • taos.tar.gz: client driver package
    • driver: TDengine client driver
    • examples: some example programs of different programming languages (C/C#/go/JDBC/MATLAB/python/R) You can run install_client.sh to install it.
  4. configure taos.cfg

    Edit taos.cfg file (full path is /etc/taos/taos.cfg by default), modify firstEP with actual TDengine server’s End Point, for example h1.tdengine.com:6030

Connect - 图2tip
  1. If the computer does not run the TDengine service but installs the TDengine client driver, then you need to config firstEP in taos.cfg only, and there is no need to configure FQDN;
  2. If you encounter the “Unable to resolve FQDN” error, please make sure the FQDN in the /etc/hosts file of the current computer is correctly configured, or the DNS service is correctly configured.

  3. Download the client installation package

    Download TDengine

    TDengine Database

    Enter your email to receive a download link

    I would like to receive TDengine news and communications at this address.

    Submit

    Close

    All Downloads

  4. Execute the installer, select the default value as prompted, and complete the installation

  5. Installation path

    The default installation path is C:\TDengine, including the following files (directories).

    • taos.exe: TDengine CLI command-line program
    • taosadapter.exe: server-side executable that provides RESTful services and accepts writing requests from a variety of other softwares
    • taosBenchmark.exe: TDengine testing tool
    • cfg: configuration file directory
    • driver: client driver dynamic link library
    • examples: sample programs bash/C/C#/go/JDBC/Python/Node.js
    • include: header files
    • log: log file
    • unins000.exe: uninstaller
  6. configure taos.cfg

    Edit the taos.cfg file (default path C:\TDengine\cfg\taos.cfg) and change the firstEP to the End Point of the TDengine server, for example: h1.tdengine.com:6030.

Connect - 图4tip
  1. If you use FQDN to connect to the server, you must ensure the local network environment DNS is configured, or add FQDN addressing records in the hosts file, e.g., edit C:\Windows\system32\drivers\etc\hosts and add a record like the following: 192.168.1.99 h1.taosd.com..
  2. Uninstall: Run unins000.exe to uninstall the TDengine client driver.

  3. Download the client installation package

    Download TDengine

    TDengine Database

    Enter your email to receive a download link

    I would like to receive TDengine news and communications at this address.

    Submit

    Close

    All Downloads

  4. Execute the installer, select the default value as prompted, and complete the installation. If the installation is blocked, you can right-click or ctrl-click on the installation package and select Open.

  5. configure taos.cfg

    Edit taos.cfg file (full path is /etc/taos/taos.cfg by default), modify firstEP with actual TDengine server’s End Point, for example h1.tdengine.com:6030

Connect - 图6tip
  1. If the computer does not run the TDengine service but installs the TDengine client driver, then you need to config firstEP in taos.cfg only, and there is no need to configure FQDN;
  2. If you encounter the “Unable to resolve FQDN” error, please make sure the FQDN in the /etc/hosts file of the current computer is correctly configured, or the DNS service is correctly configured.

Verify

After the above installation and configuration are done and making sure TDengine service is already started and in service, the TDengine command-line interface taos can be launched to access TDengine.

  • Linux
  • Windows
  • MacOS

Execute TDengine CLI program taos directly from the Linux shell to connect to the TDengine service and enter the TDengine CLI interface, as shown in the following example.

  1. $ taos
  2. taos> show databases;
  3. name |
  4. =================================
  5. information_schema |
  6. performance_schema |
  7. db |
  8. Query OK, 3 rows in database (0.019154s)
  9. taos>

Go to the C:\TDengine directory from cmd and execute TDengine CLI program taos.exe directly to connect to the TDengine service and enter the TDengine CLI interface, for example, as follows:

  1. taos> show databases;
  2. name |
  3. =================================
  4. information_schema |
  5. performance_schema |
  6. test |
  7. Query OK, 3 rows in database (0.123000s)
  8. taos>

Execute TDengine CLI program taos directly from the macOS shell to connect to the TDengine service and enter the TDengine CLI interface, as shown in the following example.

  1. $ taos
  2. taos> show databases;
  3. name |
  4. =================================
  5. information_schema |
  6. performance_schema |
  7. db |
  8. Query OK, 3 rows in database (0.019154s)
  9. taos>

Install Connectors

  • Java
  • Python
  • Go
  • Rust
  • Node.js
  • C#
  • R
  • C
  • PHP

If maven is used to manage the projects, what needs to be done is only adding below dependency in pom.xml.

  1. <dependency>
  2. <groupId>com.taosdata.jdbc</groupId>
  3. <artifactId>taos-jdbcdriver</artifactId>
  4. <version>3.0.0</version>
  5. </dependency>

Install from PyPI using pip:

  1. pip install taospy

Install from Git URL:

  1. pip install git+https://github.com/taosdata/taos-connector-python.git

Just need to add driver-go dependency in go.mod .

go.mod

  1. module goexample
  2. go 1.17
  3. require github.com/taosdata/driver-go/v3 latest
Connect - 图7note

driver-go uses cgo to wrap the APIs provided by taosc, while cgo needs gcc to compile source code in C language, so please make sure you have proper gcc on your system.

Just need to add libtaos dependency in Cargo.toml.

Cargo.toml

  1. [dependencies]
  2. libtaos = { version = "0.4.2"}
Connect - 图8info

Rust connector uses different features to distinguish the way to establish connection. To establish REST connection, please enable rest feature.

  1. libtaos = { version = "*", features = ["rest"] }

Node.js connector provides different ways of establishing connections by providing different packages.

  1. Install Node.js Native Connector
  1. npm install @tdengine/client
Connect - 图9note

It’s recommend to use Node whose version is between node-v12.8.0 and node-v13.0.0.

  1. Install Node.js REST Connector
  1. npm install @tdengine/rest

Just need to add the reference to TDengine.Connector in the project configuration file.

csharp.csproj

  1. <Project Sdk="Microsoft.NET.Sdk">
  2. <PropertyGroup>
  3. <OutputType>Exe</OutputType>
  4. <TargetFramework>net6.0</TargetFramework>
  5. <ImplicitUsings>enable</ImplicitUsings>
  6. <Nullable>enable</Nullable>
  7. <StartupObject>TDengineExample.AsyncQueryExample</StartupObject>
  8. </PropertyGroup>
  9. <ItemGroup>
  10. <PackageReference Include="TDengine.Connector" Version="3.0.0" />
  11. </ItemGroup>
  12. </Project>

Or add by dotnet command.

  1. dotnet add package TDengine.Connector
Connect - 图10note

The sample code below are based on dotnet6.0, they may need to be adjusted if your dotnet version is not exactly same.

  1. Download taos-jdbcdriver-version-dist.jar.
  2. Install the dependency package RJDBC
  1. install.packages("RJDBC")

If the client driver (taosc) is already installed, then the C connector is already available.

Download Source Code Package and Unzip:

  1. curl -L -o php-tdengine.tar.gz https://github.com/Yurunsoft/php-tdengine/archive/refs/tags/v1.0.2.tar.gz \
  2. && mkdir php-tdengine \
  3. && tar -xzf php-tdengine.tar.gz -C php-tdengine --strip-components=1

Version number v1.0.2 is only for example, it can be replaced to any newer version, please check available version from TDengine PHP Connector Releases.

Non-Swoole Environment:

  1. phpize && ./configure && make -j && make install

Specify TDengine Location:

  1. phpize && ./configure --with-tdengine-dir=/usr/local/Cellar/tdengine/3.0.0.0 && make -j && make install

--with-tdengine-dir= is followed by the TDengine installation location. This way is useful in case TDengine location can’t be found automatically or macOS.

Swoole Environment:

  1. phpize && ./configure --enable-swoole && make -j && make install

Enable The Extension:

Option One: Add extension=tdengine in php.ini

Option Two: Specify the extension on CLI php -d extension=tdengine test.php

Establish a connection

Prior to establishing connection, please make sure TDengine is already running and accessible. The following sample code assumes TDengine is running on the same host as the client program, with FQDN configured to “localhost” and serverPort configured to “6030”.

  • Java
  • Python
  • Go
  • Rust
  • Node.js
  • C#
  • R
  • C
  • PHP

Native Connection

  1. package com.taos.example;
  2. import java.sql.Connection;
  3. import java.sql.DriverManager;
  4. import java.sql.SQLException;
  5. import java.util.Properties;
  6. import com.taosdata.jdbc.TSDBDriver;
  7. public class JNIConnectExample {
  8. public static void main(String[] args) throws SQLException {
  9. String jdbcUrl = "jdbc:TAOS://localhost:6030?user=root&password=taosdata";
  10. Properties connProps = new Properties();
  11. connProps.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
  12. connProps.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
  13. connProps.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
  14. Connection conn = DriverManager.getConnection(jdbcUrl, connProps);
  15. System.out.println("Connected");
  16. conn.close();
  17. }
  18. }
  19. // use
  20. // String jdbcUrl = "jdbc:TAOS://localhost:6030/dbName?user=root&password=taosdata";
  21. // if you want to connect a specified database named "dbName".

view source code

REST Connection

  1. public static void main(String[] args) throws SQLException {
  2. String jdbcUrl = "jdbc:TAOS-RS://localhost:6041?user=root&password=taosdata";
  3. Connection conn = DriverManager.getConnection(jdbcUrl);
  4. System.out.println("Connected");
  5. conn.close();
  6. }

view source code

When using REST connection, the feature of bulk pulling can be enabled if the size of resulting data set is huge.

Enable Bulk Pulling

  1. public static void main(String[] args) throws SQLException {
  2. String jdbcUrl = "jdbc:TAOS-RS://localhost:6041?user=root&password=taosdata";
  3. Properties connProps = new Properties();
  4. connProps.setProperty(TSDBDriver.PROPERTY_KEY_BATCH_LOAD, "true");
  5. Connection conn = DriverManager.getConnection(jdbcUrl, connProps);
  6. System.out.println("Connected");
  7. conn.close();
  8. }

view source code

More configuration about connection,please refer to Java Connector

Native Connection

  1. import taos
  2. def test_connection():
  3. # all parameters are optional.
  4. # if database is specified,
  5. # then it must exist.
  6. conn = taos.connect(host="localhost",
  7. port=6030,
  8. user="root",
  9. password="taosdata",
  10. database="log")
  11. print('client info:', conn.client_info)
  12. print('server info:', conn.server_info)
  13. conn.close()
  14. if __name__ == "__main__":
  15. test_connection()

view source code

Unified Database Access Interface

Native Connection

  1. package main
  2. import (
  3. "database/sql"
  4. "fmt"
  5. "log"
  6. _ "github.com/taosdata/driver-go/v3/taosSql"
  7. )
  8. func main() {
  9. var taosDSN = "root:taosdata@tcp(localhost:6030)/"
  10. taos, err := sql.Open("taosSql", taosDSN)
  11. if err != nil {
  12. log.Fatalln("failed to connect TDengine, err:", err)
  13. return
  14. }
  15. fmt.Println("Connected")
  16. defer taos.Close()
  17. }
  18. // use
  19. // var taosDSN = "root:taosdata@tcp(localhost:6030)/dbName"
  20. // if you want to connect a specified database named "dbName".

view source code

REST Connection

  1. package main
  2. import (
  3. "database/sql"
  4. "fmt"
  5. "log"
  6. _ "github.com/taosdata/driver-go/v3/taosRestful"
  7. )
  8. func main() {
  9. var taosDSN = "root:taosdata@http(localhost:6041)/"
  10. taos, err := sql.Open("taosRestful", taosDSN)
  11. if err != nil {
  12. log.Fatalln("failed to connect TDengine, err:", err)
  13. return
  14. }
  15. fmt.Println("Connected")
  16. defer taos.Close()
  17. }
  18. // use
  19. // var taosDSN = "root:taosdata@http(localhost:6041)/dbName"
  20. // if you want to connect a specified database named "dbName".

view source code

Advanced Features

The af package of driver-go can also be used to establish connection, with this way some advanced features of TDengine, like parameter binding and subscription, can be used.

Establish native connection using af package

  1. package main
  2. import (
  3. "fmt"
  4. "log"
  5. "github.com/taosdata/driver-go/v3/af"
  6. )
  7. func main() {
  8. conn, err := af.Open("localhost", "root", "taosdata", "", 6030)
  9. defer conn.Close()
  10. if err != nil {
  11. log.Fatalln("failed to connect, err:", err)
  12. } else {
  13. fmt.Println("connected")
  14. }
  15. }

view source code

Native Connection/REST Connection

  1. use taos::*;
  2. #[tokio::main]
  3. async fn main() -> Result<(), Error> {
  4. #[allow(unused_variables)]
  5. let taos = TaosBuilder::from_dsn("taos://")?.build()?;
  6. println!("Connected");
  7. Ok(())
  8. }

view source code

Connect - 图11note

For Rust connector, the connection depends on the feature being used. If “rest” feature is enabled, then only the implementation for “rest” is compiled and packaged.

Native Connection

  1. //A cursor also needs to be initialized in order to interact with TDengine from Node.js.
  2. const taos = require("@tdengine/client");
  3. var conn = taos.connect({
  4. host: "127.0.0.1",
  5. user: "root",
  6. password: "taosdata",
  7. config: "/etc/taos",
  8. port: 0,
  9. });
  10. var cursor = conn.cursor(); // Initializing a new cursor
  11. //Close a connection
  12. conn.close();

view source code

REST Connection

  1. const { options, connect } = require("@tdengine/rest");
  2. async function test() {
  3. options.path = "/rest/sql";
  4. options.host = "localhost";
  5. let conn = connect(options);
  6. let cursor = conn.cursor();
  7. try {
  8. let res = await cursor.query("SELECT server_version()");
  9. res.toString();
  10. } catch (err) {
  11. console.log(err);
  12. }
  13. }
  14. test();
  15. // output:
  16. // server_version() |
  17. // ===================
  18. // 3.0.0.0 |

view source code

Native Connection

  1. using TDengineDriver;
  2. namespace TDengineExample
  3. {
  4. internal class ConnectExample
  5. {
  6. static void Main(String[] args)
  7. {
  8. string host = "localhost";
  9. short port = 6030;
  10. string username = "root";
  11. string password = "taosdata";
  12. string dbname = "";
  13. var conn = TDengine.Connect(host, username, password, dbname, port);
  14. if (conn == IntPtr.Zero)
  15. {
  16. throw new Exception("Connect to TDengine failed");
  17. }
  18. else
  19. {
  20. Console.WriteLine("Connect to TDengine success");
  21. }
  22. TDengine.Close(conn);
  23. TDengine.Cleanup();
  24. }
  25. }
  26. }

view source code

WebSocket Connection

  1. using System;
  2. using TDengineWS.Impl;
  3. namespace Examples
  4. {
  5. public class WSConnExample
  6. {
  7. static int Main(string[] args)
  8. {
  9. string DSN = "ws://root:taosdata@127.0.0.1:6041/test";
  10. IntPtr wsConn = LibTaosWS.WSConnectWithDSN(DSN);
  11. if (wsConn == IntPtr.Zero)
  12. {
  13. Console.WriteLine("get WS connection failed");
  14. return -1;
  15. }
  16. else
  17. {
  18. Console.WriteLine("Establish connect success.");
  19. // close connection.
  20. LibTaosWS.WSClose(wsConn);
  21. }
  22. return 0;
  23. }
  24. }
  25. }

view source code

Native Connection

  1. library("DBI")
  2. library("rJava")
  3. library("RJDBC")
  4. args<- commandArgs(trailingOnly = TRUE)
  5. driver_path = args[1] # path to jdbc-driver for example: "/root/taos-jdbcdriver-3.0.0-dist.jar"
  6. driver = JDBC("com.taosdata.jdbc.TSDBDriver", driver_path)
  7. conn = dbConnect(driver, "jdbc:TAOS://127.0.0.1:6030/?user=root&password=taosdata")
  8. dbGetQuery(conn, "SELECT server_version()")
  9. dbDisconnect(conn)

view source code

Native Connection

  1. // compile with
  2. // gcc connect_example.c -o connect_example -ltaos
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include "taos.h"
  6. int main() {
  7. const char *host = "localhost";
  8. const char *user = "root";
  9. const char *passwd = "taosdata";
  10. // if don't want to connect to a default db, set it to NULL or ""
  11. const char *db = NULL;
  12. uint16_t port = 0; // 0 means use the default port
  13. TAOS *taos = taos_connect(host, user, passwd, db, port);
  14. if (taos == NULL) {
  15. int errno = taos_errno(NULL);
  16. char *msg = taos_errstr(NULL);
  17. printf("%d, %s\n", errno, msg);
  18. } else {
  19. printf("connected\n");
  20. taos_close(taos);
  21. }
  22. taos_cleanup();
  23. }

view source code

原生连接

  1. <?php
  2. use TDengine\Connection;
  3. use TDengine\Exception\TDengineException;
  4. try {
  5. // instantiate
  6. $host = 'localhost';
  7. $port = 6030;
  8. $username = 'root';
  9. $password = 'taosdata';
  10. $dbname = null;
  11. $connection = new Connection($host, $port, $username, $password, $dbname);
  12. // connect
  13. $connection->connect();
  14. } catch (TDengineException $e) {
  15. // throw exception
  16. throw $e;
  17. }

view source code

Connect - 图12tip

If the connection fails, in most cases it’s caused by improper configuration for FQDN or firewall. Please refer to the section “Unable to establish connection” in FAQ.