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 various programming language connectors, including official connectors for C/C++, Java, Python, Go, Node.js, C#, Rust, Lua (community-contributed), and PHP (community-contributed). These connectors support connecting to TDengine clusters using native interfaces (taosc) and REST interfaces (not supported by some languages). Community developers have also contributed several unofficial connectors, such as the 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. Directly connect to the server program taosd using the client driver taosc; this method is referred to as "native connection."
  2. Establish a connection to taosd via the REST API provided by the taosAdapter component; this method is referred to as "REST connection."
  3. Establish a connection to taosd via the WebSocket API provided by the taosAdapter component; this method is referred to as "WebSocket connection."
Figure 1. Connecting to TDengine

Regardless of the method used to establish a connection, the connectors provide similar API operations for databases and can execute SQL statements. The only difference lies in how the connection is initialized, and users should not notice any difference in usage. For various connection methods and language connector support, refer to: Feature Support.

Key differences include:

  1. For the native connection, it is necessary to ensure that the client driver taosc and the TDengine server version are compatible.
  2. With the REST connection, users do not need to install the client driver taosc, which offers cross-platform ease of use; however, users cannot experience features like data subscription and binary data types. Moreover, REST connections have the lowest performance compared to native and WebSocket connections. The REST API is stateless, and when using REST connections, users must specify the database name for tables and supertables in SQL.
  3. For the WebSocket connection, users also do not need to install the client driver taosc.
  4. To connect to cloud service instances, users must use REST or WebSocket connections.

It is recommended to use WebSocket connections.

Install the Client Driver taosc

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

Installation Steps

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

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

    2. Execute the installation script

      After extracting the package, you will see the following files (directories) in the extraction directory:

      • install_client.sh: The installation script for the application driver
      • package.tar.gz: The application driver installation package
      • driver: The TDengine application driver
      • examples: Example programs in various programming languages (C/C#/Go/JDBC/MATLAB/Python/R) Run install_client.sh to perform the installation.
    3. Configure taos.cfg

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

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

    Installation Verification

    After the installation and configuration are complete, and ensuring that the TDengine service is running normally, you can execute the TDengine command-line program taos included in the installation package to log in.

    In the Linux shell, you can directly execute taos to connect to the TDengine service and enter the TDengine CLI interface. Here is an example:

    $ taos

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

    taos>

    Install Connectors

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

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

    Establishing Connections

    Before executing this step, ensure that there is a running and accessible TDengine instance, and that the server's FQDN is configured correctly. The following example code assumes that TDengine is installed on the local machine, with the FQDN (default localhost) and serverPort (default 6030) using default configurations.

    Connection Parameters

    There are many configuration items for the connection. Before establishing the connection, we can introduce the parameters used by each language connector to establish a connection.

    The parameters for establishing a connection with the Java connector include URL and Properties.

    The standard format for TDengine's JDBC URL is: jdbc:[TAOS|TAOS-RS]://[host_name]:[port]/[database_name]?[user={user}|&password={password}|&charset={charset}|&cfgdir={config_dir}|&locale={locale}|&timezone={timezone}|&batchfetch={batchfetch}]

    For detailed parameter descriptions of URL and Properties, and how to use them, refer to URL Specification.

    Note: Adding the batchfetch parameter and setting it to true in REST connections will enable the WebSocket connection.

    WebSocket Connection

    Below are code samples for establishing a WebSocket connection using each language connector. They demonstrate how to connect to the TDengine database using the WebSocket connection method and set some parameters for the connection. The entire 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 code samples for establishing a native connection using each language connector. They demonstrate how to connect to the TDengine database using the native connection method and set some parameters for the connection. The entire process mainly involves establishing the 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 code samples for establishing a REST connection using each language connector. They demonstrate how to connect to the TDengine database using the REST connection method. The entire process mainly involves establishing the 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 configuration. For detailed troubleshooting methods, refer to Frequently Asked Questions under "If I encounter the error Unable to establish connection, what should I do?"

    Connection Pool

    Some connectors provide connection pools or can work with existing connection pool components. Using a connection pool allows applications to quickly obtain available connections from the pool, avoiding the overhead of creating and destroying connections for each operation. This not only reduces resource consumption but also improves response speed. Additionally, connection pools support connection management, such as limiting the maximum number of connections and checking connection validity, ensuring efficient and reliable use of connections. We recommend using connection pools to manage connections.

    Below are code samples for connection pool support in various language connectors.

    HikariCP

    Usage example:

    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 via HikariDataSource.getConnection(), you need to call the close() method after use; it does not actually close the connection, but returns it to the pool. For more issues related to HikariCP usage, refer to the official documentation.

    Druid

    Usage example:

    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 related to Druid usage, refer to the official documentation.