Skip to main content

Connecting to TDengine

TDengine provides a rich set of application development interfaces. To facilitate users in quickly developing their applications, TDengine supports connectors for multiple programming languages. The official connectors include support for C/C++, Java, Python, Go, Node.js, C#, Rust, Lua (community contribution), and PHP (community contribution). These connectors support connecting to the TDengine cluster using the native interface (taosc) and REST interface (not supported in some languages yet). Community developers have also contributed several unofficial connectors, such as ADO.NET connector, Lua connector, and PHP connector. Additionally, TDengine can directly call the REST API provided by taosadapter for data writing and querying operations.

Connection Methods

TDengine provides three methods for establishing connections:

  1. Direct connection between the client driver taosc and the server program taosd, referred to as "native connection" in the text below.
  2. Connection to taosd through the REST API provided by the taosAdapter component, referred to as "REST connection" in the text below.
  3. Connection to taosd through the WebSocket API provided by the taosAdapter component, referred to as "WebSocket connection" in the text below.
Figure 1. Connecting to TDengine

Regardless of the method used to establish the connection, the connectors provide the same or similar API to operate the database and can execute SQL statements. The initialization of the connection slightly differs, but users will not feel any difference in usage. For various connection methods and language connector support, please refer to: Connector Features

Key differences include:

  1. Using native connection requires ensuring that the client driver taosc and the server's TDengine version are compatible.
  2. Using REST connection does not require installing the client driver taosc, offering the advantage of cross-platform ease of use, but it lacks features like data subscription and binary data types. Additionally, compared to native and WebSocket connections, the performance of REST connections is the lowest. REST interfaces are stateless. When using REST connections, it is necessary to specify the database names of tables and supertables in SQL.
  3. Using WebSocket connection also does not require installing the client driver taosc.
  4. Connecting to cloud service instances must use REST connection or WebSocket connection.

WebSocket connection is recommended

Installing the Client Driver taosc

If you choose a native connection and your application is not running on the same server as TDengine, you need to install the client driver first; otherwise, you can skip this step. To avoid incompatibility between the client driver and the server, please use consistent versions.

Installation Steps

  1. Download the client installation package
    1. Unzip the software package

      Place the package in any directory where the current user has read and write access, then execute the following command: tar -xzvf TDengine-client-VERSION.tar.gz Replace VERSION with the actual version string.

    2. Run the installation script

      After unzipping the package, you will see the following files (directories) in the unzipped directory:

      • install_client.sh: Installation script, used for applying the driver
      • package.tar.gz: Application driver installation package
      • driver: TDengine application driver
      • examples: Sample programs for various programming languages (c/C#/go/JDBC/MATLAB/python/R) Run install_client.sh to install.
    3. Configure taos.cfg

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

    tip
    1. If the TDengine service is not deployed on this machine and only the application driver is installed, then only firstEP needs to be configured in taos.cfg, there is no need to configure FQDN on this machine.
    2. To prevent the "Unable to resolve FQDN" error when connecting to the server, it is recommended to ensure that the /etc/hosts file on your machine is configured with the correct FQDN value of the server, or that the DNS service is properly configured.

    Installation Verification

    After completing the above installation and configuration, and confirming that the TDengine service has started running normally, you can log in using the TDengine command-line program taos included in the installation package.

    In the Linux shell, execute taos directly to connect to the TDengine service, entering the TDengine CLI interface, as shown below:

    $ taos

    taos> show databases;
    name |
    =================================
    information_schema |
    performance_schema |
    db |
    Query OK, 3 rows in database (0.019154s)

    taos>

    Installing Connectors

    If you are using Maven to manage your project, simply add the following dependency to your pom.xml.

    <dependency>
    <groupId>com.taosdata.jdbc</groupId>
    <artifactId>taos-jdbcdriver</artifactId>
    <version>3.4.0</version>
    </dependency>

    Establishing Connection

    Before proceeding with this step, please ensure that there is a running TDengine that can be accessed, and that the server's FQDN is configured correctly. The following example code assumes that TDengine is installed on the local machine, and that the FQDN (default localhost) and serverPort (default 6030) are using the default configuration.

    Connection Parameters

    There are many configuration options for connecting, so before establishing a connection, let's first introduce the parameters used by the connectors of each language to establish a connection.

    The parameters for establishing a connection with the Java connector are URL and Properties.
    The JDBC URL format for TDengine is: jdbc:[TAOS|TAOS-WS|TAOS-RS]://[host_name]:[port]/[database_name]?[user={user}|&password={password}|&charset={charset}|&cfgdir={config_dir}|&locale={locale}|&timezone={timezone}|&batchfetch={batchfetch}]

    For detailed explanations of URL and Properties parameters and how to use them, see URL specifications

    WebSocket Connection

    Below are code examples for establishing WebSocket connections in various language connectors. It demonstrates how to connect to the TDengine database using WebSocket and set some parameters for the connection. The whole process mainly involves establishing the database connection and handling exceptions.

    public static void main(String[] args) throws Exception {
    // use
    // String jdbcUrl =
    // "jdbc:TAOS-WS://localhost:6041/dbName?user=root&password=taosdata";
    // if you want to connect a specified database named "dbName".
    String jdbcUrl = "jdbc:TAOS-WS://localhost:6041?user=root&password=taosdata";
    Properties connProps = new Properties();
    connProps.setProperty(TSDBDriver.PROPERTY_KEY_ENABLE_AUTO_RECONNECT, "true");
    connProps.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
    connProps.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");

    try (Connection conn = DriverManager.getConnection(jdbcUrl, connProps)) {
    System.out.println("Connected to " + jdbcUrl + " successfully.");

    // you can use the connection for execute SQL here

    } catch (Exception ex) {
    // please refer to the JDBC specifications for detailed exceptions info
    System.out.printf("Failed to connect to %s, %sErrMessage: %s%n",
    jdbcUrl,
    ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "",
    ex.getMessage());
    // Print stack trace for context in examples. Use logging in production.
    ex.printStackTrace();
    throw ex;
    }
    }

    view source code

    Native Connection

    Below are examples of code for establishing native connections in various languages. It demonstrates how to connect to the TDengine database using a native connection method and set some parameters for the connection. The entire process mainly involves establishing a database connection and handling exceptions.

    public static void main(String[] args) throws Exception {
    // use
    // String jdbcUrl =
    // "jdbc:TAOS://localhost:6030/dbName?user=root&password=taosdata";
    // if you want to connect a specified database named "dbName".
    String jdbcUrl = "jdbc:TAOS://localhost:6030?user=root&password=taosdata";
    Properties connProps = new Properties();
    connProps.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
    connProps.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
    connProps.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");

    try (Connection conn = DriverManager.getConnection(jdbcUrl, connProps)) {
    System.out.println("Connected to " + jdbcUrl + " successfully.");

    // you can use the connection for execute SQL here

    } catch (Exception ex) {
    // please refer to the JDBC specifications for detailed exceptions info
    System.out.printf("Failed to connect to %s, %sErrMessage: %s%n",
    jdbcUrl,
    ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "",
    ex.getMessage());
    // Print stack trace for context in examples. Use logging in production.
    ex.printStackTrace();
    throw ex;
    }
    }

    view source code

    REST Connection

    Below are examples of code for establishing REST connections in various languages. It demonstrates how to connect to the TDengine database using a REST connection method. The entire process mainly involves establishing a database connection and handling exceptions.

    public static void main(String[] args) throws Exception {
    String jdbcUrl = "jdbc:TAOS-RS://localhost:6041?user=root&password=taosdata";
    try (Connection conn = DriverManager.getConnection(jdbcUrl)) {
    System.out.println("Connected to " + jdbcUrl + " successfully.");

    // you can use the connection for execute SQL here

    } catch (Exception ex) {
    // please refer to the JDBC specifications for detailed exceptions info
    System.out.printf("Failed to connect to %s, %sErrMessage: %s%n",
    jdbcUrl,
    ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "",
    ex.getMessage());
    // Print stack trace for context in examples. Use logging in production.
    ex.printStackTrace();
    throw ex;
    }
    }

    view source code

    tip

    If the connection fails, in most cases it is due to incorrect FQDN or firewall settings. For detailed troubleshooting methods, please see "Encountering the error 'Unable to establish connection, what should I do?'" in the "Common Questions and Feedback".

    Connection Pool

    Some connectors offer a connection pool, or can be used in conjunction with existing connection pool components. By using a connection pool, applications can quickly obtain available connections from the pool, avoiding the overhead of creating and destroying connections with each operation. This not only reduces resource consumption but also improves response speed. Additionally, connection pools support the management of connections, such as limiting the maximum number of connections and checking the validity of connections, ensuring efficient and reliable use of connections. We recommend managing connections using a connection pool.
    Below are code examples of connection pool support for various language connectors.

    HikariCP

    Example usage is as follows:

    public static void main(String[] args) throws Exception {
    HikariConfig config = new HikariConfig();
    // jdbc properties
    config.setJdbcUrl("jdbc:TAOS://127.0.0.1:6030/log");
    config.setUsername("root");
    config.setPassword("taosdata");
    // connection pool configurations
    config.setMinimumIdle(10); // minimum number of idle connection
    config.setMaximumPoolSize(10); // maximum number of connection in the pool
    config.setConnectionTimeout(30000); // maximum wait milliseconds for get connection from pool
    config.setMaxLifetime(0); // maximum life time for each connection
    config.setIdleTimeout(0); // max idle time for recycle idle connection
    config.setConnectionTestQuery("SELECT SERVER_VERSION()"); // validation query

    HikariDataSource dataSource = new HikariDataSource(config); // create datasource

    Connection connection = dataSource.getConnection(); // get connection
    Statement statement = connection.createStatement(); // get statement

    // query or insert
    // ...
    statement.close();
    connection.close(); // put back to connection pool
    dataSource.close();
    }

    view source code

    After obtaining a connection through HikariDataSource.getConnection(), you need to call the close() method after use, which actually does not close the connection but returns it to the pool. For more issues about using HikariCP, please see the official documentation.

    Druid

    Example usage is as follows:

    public static void main(String[] args) throws Exception {
    String url = "jdbc:TAOS://127.0.0.1:6030/log";

    DruidDataSource dataSource = new DruidDataSource();
    // jdbc properties
    dataSource.setDriverClassName("com.taosdata.jdbc.TSDBDriver");
    dataSource.setUrl(url);
    dataSource.setUsername("root");
    dataSource.setPassword("taosdata");
    // pool configurations
    dataSource.setInitialSize(10);
    dataSource.setMinIdle(10);
    dataSource.setMaxActive(10);
    dataSource.setMaxWait(30000);
    dataSource.setValidationQuery("SELECT SERVER_VERSION()");

    Connection connection = dataSource.getConnection(); // get connection
    Statement statement = connection.createStatement(); // get statement
    // query or insert
    // ...

    statement.close();
    connection.close(); // put back to connection pool
    dataSource.close();
    }

    view source code

    For more issues about using Druid, please see the official documentation.