Connect

Any application programs running on any kind of platform can access TDengine through the REST API provided by TDengine. For details, please refer to REST API. Additionally, application programs can use the connectors of multiple programming languages including C/C++, Java, Python, Go, Node.js, C#, Rust to access TDengine. This chapter describes how to establish a connection to TDengine and briefly introduces how to install and use connectors. TDengine community also provides connectors in LUA and PHP languages. For details about the connectors, please refer to Connectors.

Establish Connection

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

  1. Connection through the REST API provided by the taosAdapter component, this way is called “REST connection” hereinafter.
  2. Connection through the TDengine client driver (taosc), this way is called “Native connection” hereinafter.

Key differences:

  1. The TDengine client driver (taosc) has the highest performance with all the features of TDengine like Parameter Binding, Subscription, etc.
  2. The TDengine client driver (taosc) is not supported across all platforms, and applications built on taosc may need to be modified when updating taosc to newer versions.
  3. The REST connection is more accessible with cross-platform support, however it results in a 30% performance downgrade.

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
  1. Download the TDengine client installation package

    Enter your email to receive the download link

    TDengine Database

    encn

    Agree to TDengine to contact me via this email addressDownload

    Close

    All Packages

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

    Enter your email to receive the download link

    TDengine Database

    encn

    Agree to TDengine to contact me via this email addressDownload

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

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

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. Welcome to the TDengine shell from Linux, Client Version:2.0.5.0
  3. Copyright (c) 2017 by TAOS Data, Inc. All rights reserved.
  4. taos> show databases;
  5. name | created_time | ntables | vgroups | replica | quorum | days | keep1,keep2,keep(D) | cache(MB)| blocks | minrows | maxrows | wallevel | fsync | comp | precision | status |
  6. =========================================================================================================================================================================================================================
  7. test | 2020-10-14 10:35:48.617 | 10 | 1 | 1 | 1 | 2 | 3650,3650,3650 | 16| 6 | 100 | 4096 | 1 | 3000 | 2 | ms | ready |
  8. log | 2020-10-12 09:08:21.651 | 4 | 1 | 1 | 1 | 10 | 30,30,30 | 1| 3 | 100 | 4096 | 1 | 3000 | 2 | us | ready |
  9. Query OK, 2 row(s) in set (0.001198s)
  10. 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. C:\TDengine>taos
  2. Welcome to the TDengine shell from Linux, Client Version:2.0.5.0
  3. Copyright (c) 2017 by TAOS Data, Inc. All rights reserved.
  4. taos> show databases;
  5. name | created_time | ntables | vgroups | replica | quorum | days | keep1,keep2,keep(D) | cache(MB) | blocks | minrows | maxrows | wallevel | fsync | comp | precision | status |
  6. ===================================================================================================================================================================================================================================================================
  7. test | 2020-10-14 10:35:48.617 | 10 | 1 | 1 | 1 | 2 | 3650,3650,3650 | 16 | 6 | 100 | 4096 | 1 | 3000 | 2 | ms | ready |
  8. log | 2020-10-12 09:08:21.651 | 4 | 1 | 1 | 1 | 10 | 30,30,30 | 1 | 3 | 100 | 4096 | 1 | 3000 | 2 | us | ready |
  9. Query OK, 2 row(s) in set (0.045000s)
  10. 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>2.0.38</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/v2 latest

view source code

Connect - 图5note

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 - 图6info

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 i td2.0-connector
Connect - 图7note

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 i td2.0-rest-connector

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="1.0.6" />
  11. </ItemGroup>
  12. </Project>

Or add by dotnet command.

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

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/2.4.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 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

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. _ "github.com/taosdata/driver-go/v2/taosSql"
  6. )
  7. func main() {
  8. var taosDSN = "root:taosdata@tcp(localhost:6030)/"
  9. taos, err := sql.Open("taosSql", taosDSN)
  10. if err != nil {
  11. fmt.Println("failed to connect TDengine, err:", err)
  12. return
  13. }
  14. fmt.Println("Connected")
  15. defer taos.Close()
  16. }
  17. // use
  18. // var taosDSN = "root:taosdata@tcp(localhost:6030)/dbName"
  19. // 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. _ "github.com/taosdata/driver-go/v2/taosRestful"
  6. )
  7. func main() {
  8. var taosDSN = "root:taosdata@http(localhost:6041)/"
  9. taos, err := sql.Open("taosRestful", taosDSN)
  10. if err != nil {
  11. fmt.Println("failed to connect TDengine, err:", err)
  12. return
  13. }
  14. fmt.Println("Connected")
  15. defer taos.Close()
  16. }
  17. // use
  18. // var taosDSN = "root:taosdata@http(localhost:6041)/dbName"
  19. // 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. "github.com/taosdata/driver-go/v2/af"
  5. )
  6. func main() {
  7. conn, err := af.Open("localhost", "root", "taosdata", "", 6030)
  8. defer conn.Close()
  9. if err != nil {
  10. fmt.Println("failed to connect, err:", err)
  11. } else {
  12. fmt.Println("connected")
  13. }
  14. }

view source code

Native Connection/REST Connection

  1. use libtaos::*;
  2. fn taos_connect() -> Result<Taos, Error> {
  3. TaosCfgBuilder::default()
  4. .ip("localhost")
  5. .user("root")
  6. .pass("taosdata")
  7. // .db("log") // remove comment if you want to connect to database log by default.
  8. .port(6030u16)
  9. .build()
  10. .expect("TaosCfg builder error")
  11. .connect()
  12. }
  13. fn main() {
  14. #[allow(unused_variables)]
  15. let taos = taos_connect().unwrap();
  16. println!("Connected")
  17. }

view source code

Connect - 图9note

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. const taos = require("td2.0-connector");
  2. var conn = taos.connect({
  3. host: "localhost",
  4. port: 6030,
  5. user: "root",
  6. password: "taosdata",
  7. });
  8. conn.close();
  9. // run with: node connect.js
  10. // output:
  11. // Successfully connected to TDengine

view source code

REST Connection

  1. const { options, connect } = require("td2.0-rest-connector");
  2. async function test() {
  3. options.path = "/rest/sqlt";
  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. // 2.4.0.12 |

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. Console.WriteLine("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

Connect - 图10info

C# connector supports only native connection for now.

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

Connect - 图11tip

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.