Skip to main content

Connecting to TDengine

TDengine TSDB provides a rich set of application development interfaces. To facilitate users in quickly developing applications, it supports connectors for multiple programming languages — among which the official ones include those for C/C++, Java, Python, Go, Node.js, C#, and Rust. Community developers have also contributed several unofficial connectors, such as the ADO.NET connector, Lua connector, and PHP connector. These connectors support connecting to the TDengine TSDB cluster via the native interface and WebSocket interface. Additionally, users can directly call the REST API interfaces provided by taosAdapter to access TDengine TSDB for data writing and query operations.

Connection Methods

The following is the architecture diagram of the connection methods between TDengine TSDB client and server: TDengine client library architecture

As shown in the architecture diagram above, there are three ways to access TDengine TSDB:

  1. WebSocket connection: Establish a connection with taosd through the WebSocket API provided by the taosAdapter component using a connector. This connection method is referred to as "WebSocket connection" in the following text. WebSocket connection is recommended.
  2. Native connection: Establish a direct connection with the server program taosd through the client driver taosc using a connector. This connection method is referred to as "native connection" in the following text.
  3. REST API: Establish a connection with taosd by directly calling the REST API provided by the taosAdapter component using an HTTP client, without using a connector. This connection method is referred to as "REST API" in the following text.

Note: The client driver taosc includes C native and WebSocket connectors. Applications developed in C/C++ language must depend on the client driver taosc.

For both WebSocket connections and native connections, connectors provide the same or similar APIs for database operations. The only slight difference lies in the connection initialization methods, so users will not perceive any difference in usage.

For the support status of various connection methods and connectors for different languages, please refer to Connector Features.

The key differences are:

  1. When using a native connection, the version of the client driver taosc must be consistent with that of the server-side TDengine TSDB.
  2. When using a WebSocket connection, except for C/C++ and ODBC connectors, users do not need to install the client driver taosc. Even if the client driver taosc is required, there is no need to ensure its version is consistent with that of the server-side TDengine TSDB.
  3. To connect to a cloud service instance, a WebSocket connection must be used.
  4. REST API only provides the function of executing SQL, and does not support parameter binding or data subscription.

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.5.2</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-WS://127.0.0.1:6041/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

    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-WS://127.0.0.1:6041/log";

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

    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.