TDengine Java Connector

taos-jdbcdriver is the official Java connector for TDengine. Java developers can use it to develop applications that access data in TDengine. taos-jdbcdriver implements standard JDBC driver interfaces and two connection methods: One is native connection, which connects to TDengine instances natively through the TDengine client driver (taosc), supporting data writing, querying, subscriptions, schemaless writing, and bind interface. The second is REST connection which is implemented through taosAdapter. The set of features implemented by the REST connection differs slightly from those implemented by the native connection.

TDengine Database Connector Java

The preceding figure shows the two ways in which a Java application can access TDengine.

  • JDBC native connection: Java applications use TSDBDriver on physical node 1 (pnode1) to call client-driven directly (libtaos.so or taos.dll) APIs to send writing and query requests to taosd instances located on physical node 2 (pnode2).
  • JDBC REST connection: The Java application encapsulates the SQL as a REST request via RestfulDriver, sends it to the REST server (taosAdapter) on physical node 2. taosAdapter forwards the request to TDengine server and returns the result.

The REST connection, which does not rely on TDengine client drivers, is more convenient and flexible, in addition to being cross-platform. However the performance is about 30% lower than that of the native connection.

Java - 图2info

TDengine’s JDBC driver implementation is as consistent as possible with the relational database driver. Still, there are differences in the use scenarios and technical characteristics of TDengine and relational object databases. So ‘taos-jdbcdriver’ also has some differences from traditional JDBC drivers. It is important to keep the following points in mind:

  • TDengine does not currently support delete operations for individual data records.
  • Transactional operations are not currently supported.

Supported platforms

Native connections are supported on the same platforms as the TDengine client driver. REST connection supports all platforms that can run Java.

Version support

Please refer to version support list

TDengine DataType vs. Java DataType

TDengine currently supports timestamp, number, character, Boolean type, and the corresponding type conversion with Java is as follows:

TDengine DataTypeJDBCType
TIMESTAMPjava.sql.Timestamp
INTjava.lang.Integer
BIGINTjava.lang.Long
FLOATjava.lang.Float
DOUBLEjava.lang.Double
SMALLINTjava.lang.Short
TINYINTjava.lang.Byte
BOOLjava.lang.Boolean
BINARYbyte array
NCHARjava.lang.String
JSONjava.lang.String

Note: Only TAG supports JSON types

Installation Steps

Pre-installation preparation

Before using Java Connector to connect to the database, the following conditions are required.

  • Java 1.8 or above runtime environment and Maven 3.6 or above installed
  • TDengine client driver installed (required for native connections, not required for REST connections), please refer to Installing Client Driver

Install the connectors

  • Install via Maven
  • Build from source code

taos-jdbcdriver has been published on the Sonatype Repository and synchronized to other major repositories.

Add following dependency in the pom.xml file of your Maven project:

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

You can build Java connector from source code after cloning the TDengine project:

  1. git clone https://github.com/taosdata/taos-connector-jdbc.git
  2. cd taos-connector-jdbc
  3. mvn clean install -Dmaven.test.skip=true

After you have compiled taos-jdbcdriver, the taos-jdbcdriver-3.0.*-dist.jar file is created in the target directory. The compiled JAR file is automatically stored in your local Maven repository.

Establishing a connection

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

For establishing connections, native connections differ slightly from REST connections.

  • native connection
  • REST connection
  1. Class.forName("com.taosdata.jdbc.TSDBDriver");
  2. String jdbcUrl = "jdbc:TAOS://taosdemo.com:6030/test?user=root&password=taosdata";
  3. Connection conn = DriverManager.getConnection(jdbcUrl);

In the above example, TSDBDriver, which uses a JDBC native connection, establishes a connection to a hostname taosdemo.com, port 6030 (the default port for TDengine), and a database named test. In this URL, the user name user is specified as root, and the password is taosdata.

Note: With JDBC native connections, taos-jdbcdriver relies on the client driver (libtaos.so on Linux; taos.dll on Windows; libtaos.dylib on macOS).

The configuration parameters in the URL are as follows:

  • user: Log in to the TDengine username. The default value is ‘root’.
  • password: User login password, the default value is ‘taosdata’.
  • cfgdir: client configuration file directory path, default ‘/etc/taos’ on Linux OS, ‘C:/TDengine/cfg’ on Windows OS, ‘/etc/taos’ on macOS.
  • charset: The character set used by the client, the default value is the system character set.
  • locale: Client locale, by default, use the system’s current locale.
  • timezone: The time zone used by the client, the default value is the system’s current time zone.
  • batchfetch: true: pulls result sets in batches when executing queries; false: pulls result sets row by row. The default value is true. Enabling batch pulling and obtaining a batch of data can improve query performance when the query data volume is large.
  • batchErrorIgnore:true: When executing statement executeBatch, if there is a SQL execution failure in the middle, the following SQL will continue to be executed. false: No more statements after the failed SQL are executed. The default value is: false.

Connect using the TDengine client-driven configuration file

When you use a JDBC native connection to connect to a TDengine cluster, you can use the TDengine client driver configuration file to specify parameters such as firstEp and secondEp of the cluster in the configuration file as below:

  1. Do not specify hostname and port in Java applications.
  1. public Connection getConn() throws Exception{
  2. Class.forName("com.taosdata.jdbc.TSDBDriver");
  3. String jdbcUrl = "jdbc:TAOS://:/test?user=root&password=taosdata";
  4. Properties connProps = new Properties();
  5. connProps.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
  6. connProps.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
  7. connProps.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
  8. Connection conn = DriverManager.getConnection(jdbcUrl, connProps);
  9. return conn;
  10. }
  1. specify the firstEp and the secondEp in the configuration file taos.cfg
  1. # first fully qualified domain name (FQDN) for TDengine system
  2. firstEp cluster_node1:6030
  3. # second fully qualified domain name (FQDN) for TDengine system, for cluster only
  4. secondEp cluster_node2:6030
  5. # default system charset
  6. # charset UTF-8
  7. # system locale
  8. # locale en_US.UTF-8

In the above example, JDBC uses the client’s configuration file to establish a connection to a hostname cluster_node1, port 6030, and a database named test. When the firstEp node in the cluster fails, JDBC attempts to connect to the cluster using secondEp.

In TDengine, as long as one node in firstEp and secondEp is valid, the connection to the cluster can be established normally.

The configuration file here refers to the configuration file on the machine where the application that calls the JDBC Connector is located, the default path is /etc/taos/taos.cfg on Linux, the default path is C://TDengine/cfg/taos.cfg on Windows, and the default path is /etc/taos/taos.cfg on macOS.

  1. Class.forName("com.taosdata.jdbc.rs.RestfulDriver");
  2. String jdbcUrl = "jdbc:TAOS-RS://taosdemo.com:6041/test?user=root&password=taosdata";
  3. Connection conn = DriverManager.getConnection(jdbcUrl);

In the above example, a RestfulDriver with a JDBC REST connection is used to establish a connection to a database named test with hostname taosdemo.com on port 6041. The URL specifies the user name as root and the password as taosdata.

There is no dependency on the client driver when Using a JDBC REST connection. Compared to a JDBC native connection, only the following are required:

  1. driverClass specified as “com.taosdata.jdbc.rs.RestfulDriver”.
  2. jdbcUrl starting with “jdbc:TAOS-RS://“.
  3. use 6041 as the connection port.

The configuration parameters in the URL are as follows:

  • user: Log in to the TDengine username. The default value is ‘root’.
  • password: User login password, the default value is ‘taosdata’.
  • batchfetch: true: pulls result sets in batches when executing queries; false: pulls result sets row by row. The default value is: false. batchfetch uses HTTP for data transfer. JDBC REST supports batch pulls. taos-jdbcdriver and TDengine transfer data via WebSocket connection. Compared with HTTP, WebSocket enables JDBC REST connection to support large data volume querying and improve query performance.
  • charset: specify the charset to parse the string, this parameter is valid only when set batchfetch to true.
  • batchErrorIgnore: true: when executing executeBatch of Statement, if one SQL execution fails in the middle, continue to execute the following SQL. false: no longer execute any statement after the failed SQL. The default value is: false.
  • httpConnectTimeout: REST connection timeout in milliseconds, the default value is 5000 ms.
  • httpSocketTimeout: socket timeout in milliseconds, the default value is 5000 ms. It only takes effect when batchfetch is false.
  • messageWaitTimeout: message transmission timeout in milliseconds, the default value is 3000 ms. It only takes effect when batchfetch is true.
  • useSSL: connecting Securely Using SSL. true: using SSL connection, false: not using SSL connection.

Note: Some configuration items (e.g., locale, timezone) do not work in the REST connection.

Java - 图3note
  • Unlike the native connection method, the REST interface is stateless. When using the JDBC REST connection, you need to specify the database name of the table and super table in SQL. For example:
  1. INSERT INTO test.t1 USING test.weather (ts, temperature) TAGS('California.SanFrancisco') VALUES(now, 24.6);
  • If the dbname is specified in the URL, the JDBC REST connection uses /rest/sql/dbname as the default URL for RESTful requests. In this case, it is not necessary to specify the dbname in SQL. For example, if the URL is jdbc:TAOS-RS://127.0.0.1:6041/test, then the SQL can be executed: insert into test using weather(ts, temperature) tags(‘California.SanFrancisco’) values(now, 24.6);

Specify the URL and Properties to get the connection

In addition to getting the connection from the specified URL, you can use Properties to specify parameters when the connection is established.

Note:

  • The client parameter set in the application is process-level. If you want to update the parameters of the client, you need to restart the application. This is because the client parameter is a global parameter that takes effect only the first time the application is set.
  • The following sample code is based on taos-jdbcdriver-3.0.0.
  1. public Connection getConn() throws Exception{
  2. Class.forName("com.taosdata.jdbc.TSDBDriver");
  3. String jdbcUrl = "jdbc:TAOS://taosdemo.com:6030/test?user=root&password=taosdata";
  4. Properties connProps = new Properties();
  5. connProps.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
  6. connProps.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
  7. connProps.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
  8. connProps.setProperty("debugFlag", "135");
  9. connProps.setProperty("maxSQLLength", "1048576");
  10. Connection conn = DriverManager.getConnection(jdbcUrl, connProps);
  11. return conn;
  12. }
  13. public Connection getRestConn() throws Exception{
  14. Class.forName("com.taosdata.jdbc.rs.RestfulDriver");
  15. String jdbcUrl = "jdbc:TAOS-RS://taosdemo.com:6041/test?user=root&password=taosdata";
  16. Properties connProps = new Properties();
  17. connProps.setProperty(TSDBDriver.PROPERTY_KEY_BATCH_LOAD, "true");
  18. Connection conn = DriverManager.getConnection(jdbcUrl, connProps);
  19. return conn;
  20. }

In the above example, a connection is established to taosdemo.com, port is 6030/6041, and database named test. The connection specifies the user name as root and the password as taosdata in the URL and specifies the character set, language environment, time zone, and whether to enable bulk fetching in the connProps.The url specifies the user name as root and the password as taosdata.

The configuration parameters in properties are as follows.

  • TSDBDriver.PROPERTY_KEY_USER: login TDengine user name, default value ‘root’.
  • TSDBDriver.PROPERTY_KEY_PASSWORD: user login password, default value ‘taosdata’.
  • TSDBDriver.PROPERTY_KEY_BATCH_LOAD: true: pull the result set in batch when executing query; false: pull the result set row by row. The default value is: false.
  • TSDBDriver.PROPERTY_KEY_BATCH_ERROR_IGNORE: true: when executing executeBatch of Statement, if there is a SQL execution failure in the middle, continue to execute the following sql. false: no longer execute any statement after the failed SQL. The default value is: false.
  • TSDBDriver.PROPERTY_KEY_CONFIG_DIR: only works when using JDBC native connection. Client configuration file directory path, default value /etc/taos on Linux OS, default value C:/TDengine/cfg on Windows OS, default value /etc/taos on macOS.
  • TSDBDriver.PROPERTY_KEY_CHARSET: In the character set used by the client, the default value is the system character set.
  • TSDBDriver.PROPERTY_KEY_LOCALE: this only takes effect when using JDBC native connection. Client language environment, the default value is system current locale.
  • TSDBDriver.PROPERTY_KEY_TIME_ZONE: only takes effect when using JDBC native connection. In the time zone used by the client, the default value is the system’s current time zone.
  • TSDBDriver.HTTP_CONNECT_TIMEOUT: REST connection timeout in milliseconds, the default value is 5000 ms. It only takes effect when using JDBC REST connection.
  • TSDBDriver.HTTP_SOCKET_TIMEOUT: socket timeout in milliseconds, the default value is 5000 ms. It only takes effect when using JDBC REST connection and batchfetch is false.
  • TSDBDriver.PROPERTY_KEY_MESSAGE_WAIT_TIMEOUT: message transmission timeout in milliseconds, the default value is 3000 ms. It only takes effect when using JDBC REST connection and batchfetch is true.
  • TSDBDriver.PROPERTY_KEY_USE_SSL: connecting Securely Using SSL. true: using SSL connection, false: not using SSL connection. It only takes effect when using JDBC REST connection. For JDBC native connections, you can specify other parameters, such as log level, SQL length, etc., by specifying URL and Properties. For more detailed configuration, please refer to Client Configuration.

Priority of configuration parameters

If the configuration parameters are duplicated in the URL, Properties, or client configuration file, the priority of the parameters, from highest to lowest, are as follows:

  1. JDBC URL parameters, as described above, can be specified in the parameters of the JDBC URL.
  2. Properties connProps
  3. the configuration file taos.cfg of the TDengine client driver when using a native connection

For example, if you specify the password as taosdata in the URL and specify the password as taosdemo in the Properties simultaneously, JDBC will use the password in the URL to establish the connection.

Usage examples

Create database and tables

  1. Statement stmt = conn.createStatement();
  2. // create database
  3. stmt.executeUpdate("create database if not exists db");
  4. // use database
  5. stmt.executeUpdate("use db");
  6. // create table
  7. stmt.executeUpdate("create table if not exists tb (ts timestamp, temperature int, humidity float)");

Note: If you do not use use db to specify the database, all subsequent operations on the table need to add the database name as a prefix, such as db.tb.

插入数据

  1. // insert data
  2. int affectedRows = stmt.executeUpdate("insert into tb values(now, 23, 10.3) (now + 1s, 20, 9.3)");
  3. System.out.println("insert " + affectedRows + " rows.");

now is an internal function. The default is the current time of the client’s computer. now + 1s represents the current time of the client plus 1 second, followed by the number representing the unit of time: a (milliseconds), s (seconds), m (minutes), h (hours), d (days), w (weeks), n (months), y (years).

Querying data

  1. // insert data
  2. ResultSet resultSet = stmt.executeQuery("select * from tb");
  3. Timestamp ts = null;
  4. int temperature = 0;
  5. float humidity = 0;
  6. while(resultSet.next()){
  7. ts = resultSet.getTimestamp(1);
  8. temperature = resultSet.getInt(2);
  9. humidity = resultSet.getFloat("humidity");
  10. System.out.printf("%s, %d, %s\n", ts, temperature, humidity);
  11. }

The query is consistent with operating a relational database. When using subscripts to get the contents of the returned fields, you have to start from 1. However, we recommend using the field names to get the values of the fields in the result set.

Handling exceptions

After an error is reported, the error message and error code can be obtained through SQLException.

  1. try (Statement statement = connection.createStatement()) {
  2. // executeQuery
  3. ResultSet resultSet = statement.executeQuery(sql);
  4. // print result
  5. printResult(resultSet);
  6. } catch (SQLException e) {
  7. System.out.println("ERROR Message: " + e.getMessage());
  8. System.out.println("ERROR Code: " + e.getErrorCode());
  9. e.printStackTrace();
  10. }

There are three types of error codes that the JDBC connector can report: - Error code of the JDBC driver itself (error code between 0x2301 and 0x2350), - Error code of the native connection method (error code between 0x2351 and 0x2400), and - Error code of other TDengine function modules.

For specific error codes, please refer to.

Writing data via parameter binding

TDengine has significantly improved the bind APIs to support data writing (INSERT) scenarios. Writing data in this way avoids the resource consumption of SQL syntax parsing, resulting in significant write performance improvements in many cases.

Note:

  • JDBC REST connections do not currently support bind interface
  • The following sample code is based on taos-jdbcdriver-3.0.0
  • The setString method should be called for binary type data, and the setNString method should be called for nchar type data
  • both setString and setNString require the user to declare the width of the corresponding column in the size parameter of the table definition
  1. public class ParameterBindingDemo {
  2. private static final String host = "127.0.0.1";
  3. private static final Random random = new Random(System.currentTimeMillis());
  4. private static final int BINARY_COLUMN_SIZE = 20;
  5. private static final String[] schemaList = {
  6. "create table stable1(ts timestamp, f1 tinyint, f2 smallint, f3 int, f4 bigint) tags(t1 tinyint, t2 smallint, t3 int, t4 bigint)",
  7. "create table stable2(ts timestamp, f1 float, f2 double) tags(t1 float, t2 double)",
  8. "create table stable3(ts timestamp, f1 bool) tags(t1 bool)",
  9. "create table stable4(ts timestamp, f1 binary(" + BINARY_COLUMN_SIZE + ")) tags(t1 binary(" + BINARY_COLUMN_SIZE + "))",
  10. "create table stable5(ts timestamp, f1 nchar(" + BINARY_COLUMN_SIZE + ")) tags(t1 nchar(" + BINARY_COLUMN_SIZE + "))"
  11. };
  12. private static final int numOfSubTable = 10, numOfRow = 10;
  13. public static void main(String[] args) throws SQLException {
  14. String jdbcUrl = "jdbc:TAOS://" + host + ":6030/";
  15. Connection conn = DriverManager.getConnection(jdbcUrl, "root", "taosdata");
  16. init(conn);
  17. bindInteger(conn);
  18. bindFloat(conn);
  19. bindBoolean(conn);
  20. bindBytes(conn);
  21. bindString(conn);
  22. conn.close();
  23. }
  24. private static void init(Connection conn) throws SQLException {
  25. try (Statement stmt = conn.createStatement()) {
  26. stmt.execute("drop database if exists test_parabind");
  27. stmt.execute("create database if not exists test_parabind");
  28. stmt.execute("use test_parabind");
  29. for (int i = 0; i < schemaList.length; i++) {
  30. stmt.execute(schemaList[i]);
  31. }
  32. }
  33. }
  34. private static void bindInteger(Connection conn) throws SQLException {
  35. String sql = "insert into ? using stable1 tags(?,?,?,?) values(?,?,?,?,?)";
  36. try (TSDBPreparedStatement pstmt = conn.prepareStatement(sql).unwrap(TSDBPreparedStatement.class)) {
  37. for (int i = 1; i <= numOfSubTable; i++) {
  38. // set table name
  39. pstmt.setTableName("t1_" + i);
  40. // set tags
  41. pstmt.setTagByte(0, Byte.parseByte(Integer.toString(random.nextInt(Byte.MAX_VALUE))));
  42. pstmt.setTagShort(1, Short.parseShort(Integer.toString(random.nextInt(Short.MAX_VALUE))));
  43. pstmt.setTagInt(2, random.nextInt(Integer.MAX_VALUE));
  44. pstmt.setTagLong(3, random.nextLong());
  45. // set columns
  46. ArrayList<Long> tsList = new ArrayList<>();
  47. long current = System.currentTimeMillis();
  48. for (int j = 0; j < numOfRow; j++)
  49. tsList.add(current + j);
  50. pstmt.setTimestamp(0, tsList);
  51. ArrayList<Byte> f1List = new ArrayList<>();
  52. for (int j = 0; j < numOfRow; j++)
  53. f1List.add(Byte.parseByte(Integer.toString(random.nextInt(Byte.MAX_VALUE))));
  54. pstmt.setByte(1, f1List);
  55. ArrayList<Short> f2List = new ArrayList<>();
  56. for (int j = 0; j < numOfRow; j++)
  57. f2List.add(Short.parseShort(Integer.toString(random.nextInt(Short.MAX_VALUE))));
  58. pstmt.setShort(2, f2List);
  59. ArrayList<Integer> f3List = new ArrayList<>();
  60. for (int j = 0; j < numOfRow; j++)
  61. f3List.add(random.nextInt(Integer.MAX_VALUE));
  62. pstmt.setInt(3, f3List);
  63. ArrayList<Long> f4List = new ArrayList<>();
  64. for (int j = 0; j < numOfRow; j++)
  65. f4List.add(random.nextLong());
  66. pstmt.setLong(4, f4List);
  67. // add column
  68. pstmt.columnDataAddBatch();
  69. }
  70. // execute column
  71. pstmt.columnDataExecuteBatch();
  72. }
  73. }
  74. private static void bindFloat(Connection conn) throws SQLException {
  75. String sql = "insert into ? using stable2 tags(?,?) values(?,?,?)";
  76. TSDBPreparedStatement pstmt = conn.prepareStatement(sql).unwrap(TSDBPreparedStatement.class);
  77. for (int i = 1; i <= numOfSubTable; i++) {
  78. // set table name
  79. pstmt.setTableName("t2_" + i);
  80. // set tags
  81. pstmt.setTagFloat(0, random.nextFloat());
  82. pstmt.setTagDouble(1, random.nextDouble());
  83. // set columns
  84. ArrayList<Long> tsList = new ArrayList<>();
  85. long current = System.currentTimeMillis();
  86. for (int j = 0; j < numOfRow; j++)
  87. tsList.add(current + j);
  88. pstmt.setTimestamp(0, tsList);
  89. ArrayList<Float> f1List = new ArrayList<>();
  90. for (int j = 0; j < numOfRow; j++)
  91. f1List.add(random.nextFloat());
  92. pstmt.setFloat(1, f1List);
  93. ArrayList<Double> f2List = new ArrayList<>();
  94. for (int j = 0; j < numOfRow; j++)
  95. f2List.add(random.nextDouble());
  96. pstmt.setDouble(2, f2List);
  97. // add column
  98. pstmt.columnDataAddBatch();
  99. }
  100. // execute
  101. pstmt.columnDataExecuteBatch();
  102. // close if no try-with-catch statement is used
  103. pstmt.close();
  104. }
  105. private static void bindBoolean(Connection conn) throws SQLException {
  106. String sql = "insert into ? using stable3 tags(?) values(?,?)";
  107. try (TSDBPreparedStatement pstmt = conn.prepareStatement(sql).unwrap(TSDBPreparedStatement.class)) {
  108. for (int i = 1; i <= numOfSubTable; i++) {
  109. // set table name
  110. pstmt.setTableName("t3_" + i);
  111. // set tags
  112. pstmt.setTagBoolean(0, random.nextBoolean());
  113. // set columns
  114. ArrayList<Long> tsList = new ArrayList<>();
  115. long current = System.currentTimeMillis();
  116. for (int j = 0; j < numOfRow; j++)
  117. tsList.add(current + j);
  118. pstmt.setTimestamp(0, tsList);
  119. ArrayList<Boolean> f1List = new ArrayList<>();
  120. for (int j = 0; j < numOfRow; j++)
  121. f1List.add(random.nextBoolean());
  122. pstmt.setBoolean(1, f1List);
  123. // add column
  124. pstmt.columnDataAddBatch();
  125. }
  126. // execute
  127. pstmt.columnDataExecuteBatch();
  128. }
  129. }
  130. private static void bindBytes(Connection conn) throws SQLException {
  131. String sql = "insert into ? using stable4 tags(?) values(?,?)";
  132. try (TSDBPreparedStatement pstmt = conn.prepareStatement(sql).unwrap(TSDBPreparedStatement.class)) {
  133. for (int i = 1; i <= numOfSubTable; i++) {
  134. // set table name
  135. pstmt.setTableName("t4_" + i);
  136. // set tags
  137. pstmt.setTagString(0, new String("abc"));
  138. // set columns
  139. ArrayList<Long> tsList = new ArrayList<>();
  140. long current = System.currentTimeMillis();
  141. for (int j = 0; j < numOfRow; j++)
  142. tsList.add(current + j);
  143. pstmt.setTimestamp(0, tsList);
  144. ArrayList<String> f1List = new ArrayList<>();
  145. for (int j = 0; j < numOfRow; j++) {
  146. f1List.add(new String("abc"));
  147. }
  148. pstmt.setString(1, f1List, BINARY_COLUMN_SIZE);
  149. // add column
  150. pstmt.columnDataAddBatch();
  151. }
  152. // execute
  153. pstmt.columnDataExecuteBatch();
  154. }
  155. }
  156. private static void bindString(Connection conn) throws SQLException {
  157. String sql = "insert into ? using stable5 tags(?) values(?,?)";
  158. try (TSDBPreparedStatement pstmt = conn.prepareStatement(sql).unwrap(TSDBPreparedStatement.class)) {
  159. for (int i = 1; i <= numOfSubTable; i++) {
  160. // set table name
  161. pstmt.setTableName("t5_" + i);
  162. // set tags
  163. pstmt.setTagNString(0, "California.SanFrancisco");
  164. // set columns
  165. ArrayList<Long> tsList = new ArrayList<>();
  166. long current = System.currentTimeMillis();
  167. for (int j = 0; j < numOfRow; j++)
  168. tsList.add(current + j);
  169. pstmt.setTimestamp(0, tsList);
  170. ArrayList<String> f1List = new ArrayList<>();
  171. for (int j = 0; j < numOfRow; j++) {
  172. f1List.add("California.LosAngeles");
  173. }
  174. pstmt.setNString(1, f1List, BINARY_COLUMN_SIZE);
  175. // add column
  176. pstmt.columnDataAddBatch();
  177. }
  178. // execute
  179. pstmt.columnDataExecuteBatch();
  180. }
  181. }
  182. }

The methods to set TAGS values:

  1. public void setTagNull(int index, int type)
  2. public void setTagBoolean(int index, boolean value)
  3. public void setTagInt(int index, int value)
  4. public void setTagByte(int index, byte value)
  5. public void setTagShort(int index, short value)
  6. public void setTagLong(int index, long value)
  7. public void setTagTimestamp(int index, long value)
  8. public void setTagFloat(int index, float value)
  9. public void setTagDouble(int index, double value)
  10. public void setTagString(int index, String value)
  11. public void setTagNString(int index, String value)

The methods to set VALUES columns:

  1. public void setInt(int columnIndex, ArrayList<Integer> list) throws SQLException
  2. public void setFloat(int columnIndex, ArrayList<Float> list) throws SQLException
  3. public void setTimestamp(int columnIndex, ArrayList<Long> list) throws SQLException
  4. public void setLong(int columnIndex, ArrayList<Long> list) throws SQLException
  5. public void setDouble(int columnIndex, ArrayList<Double> list) throws SQLException
  6. public void setBoolean(int columnIndex, ArrayList<Boolean> list) throws SQLException
  7. public void setByte(int columnIndex, ArrayList<Byte> list) throws SQLException
  8. public void setShort(int columnIndex, ArrayList<Short> list) throws SQLException
  9. public void setString(int columnIndex, ArrayList<String> list, int size) throws SQLException
  10. public void setNString(int columnIndex, ArrayList<String> list, int size) throws SQLException

Schemaless Writing

TDengine supports schemaless writing. It is compatible with InfluxDB’s Line Protocol, OpenTSDB’s telnet line protocol, and OpenTSDB’s JSON format protocol. For more information, see Schemaless Writing.

Note:

  • JDBC REST connections do not currently support schemaless writes
  • The following sample code is based on taos-jdbcdriver-3.0.0
  1. public class SchemalessInsertTest {
  2. private static final String host = "127.0.0.1";
  3. private static final String lineDemo = "st,t1=3i64,t2=4f64,t3=\"t3\" c1=3i64,c3=L\"passit\",c2=false,c4=4f64 1626006833639000000";
  4. private static final String telnetDemo = "stb0_0 1626006833 4 host=host0 interface=eth0";
  5. private static final String jsonDemo = "{\"metric\": \"meter_current\",\"timestamp\": 1346846400,\"value\": 10.3, \"tags\": {\"groupid\": 2, \"location\": \"California.SanFrancisco\", \"id\": \"d1001\"}}";
  6. public static void main(String[] args) throws SQLException {
  7. final String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata";
  8. try (Connection connection = DriverManager.getConnection(url)) {
  9. init(connection);
  10. SchemalessWriter writer = new SchemalessWriter(connection);
  11. writer.write(lineDemo, SchemalessProtocolType.LINE, SchemalessTimestampType.NANO_SECONDS);
  12. writer.write(telnetDemo, SchemalessProtocolType.TELNET, SchemalessTimestampType.MILLI_SECONDS);
  13. writer.write(jsonDemo, SchemalessProtocolType.JSON, SchemalessTimestampType.NOT_CONFIGURED);
  14. }
  15. }
  16. private static void init(Connection connection) throws SQLException {
  17. try (Statement stmt = connection.createStatement()) {
  18. stmt.executeUpdate("drop database if exists test_schemaless");
  19. stmt.executeUpdate("create database if not exists test_schemaless");
  20. stmt.executeUpdate("use test_schemaless");
  21. }
  22. }
  23. }

Data Subscription

The TDengine Java Connector supports subscription functionality with the following application API.

Create a Topic

  1. Connection connection = DriverManager.getConnection(url, properties);
  2. Statement statement = connection.createStatement();
  3. statement.executeUpdate("create topic if not exists topic_speed as select ts, speed from speed_table");

The three parameters of the subscribe() method have the following meanings.

  • topic_speed: the subscribed topic (name). This is the unique identifier of the subscription.
  • sql: the query statement of the subscription which can only be a select statement. Only the original data should be queried, and data can only be queried in temporal order..

The preceding example uses the SQL statement select ts, speed from speed_table and creates a subscription named topic_speed.

Create a Consumer

  1. Properties config = new Properties();
  2. config.setProperty("enable.auto.commit", "true");
  3. config.setProperty("group.id", "group1");
  4. config.setProperty("value.deserializer", "com.taosdata.jdbc.tmq.ConsumerTest.ResultDeserializer");
  5. TaosConsumer consumer = new TaosConsumer<>(config);
  • enable.auto.commit: Specifies whether to commit automatically.
  • group.id: consumer: Specifies the group that the consumer is in.
  • value.deserializer: To deserialize the results, you can inherit com.taosdata.jdbc.tmq.ReferenceDeserializer and specify the result set bean. You can also inherit com.taosdata.jdbc.tmq.Deserializer and perform custom deserialization based on the SQL result set.
  • For more information, see Consumer Parameters.

Subscribe to consume data

  1. while(true) {
  2. ConsumerRecords<ResultBean> records = consumer.poll(Duration.ofMillis(100));
  3. for (ResultBean record : records) {
  4. process(record);
  5. }
  6. }

poll obtains one message each time it is run.

Close subscriptions

  1. // Unsubscribe
  2. consumer.unsubscribe();
  3. // Close consumer
  4. consumer.close()

For more information, see Data Subscription.

Usage examples

  1. public abstract class ConsumerLoop {
  2. private final TaosConsumer<ResultBean> consumer;
  3. private final List<String> topics;
  4. private final AtomicBoolean shutdown;
  5. private final CountDownLatch shutdownLatch;
  6. public ConsumerLoop() throws SQLException {
  7. Properties config = new Properties();
  8. config.setProperty("msg.with.table.name", "true");
  9. config.setProperty("enable.auto.commit", "true");
  10. config.setProperty("group.id", "group1");
  11. config.setProperty("value.deserializer", "com.taosdata.jdbc.tmq.ConsumerTest.ConsumerLoop$ResultDeserializer");
  12. this.consumer = new TaosConsumer<>(config);
  13. this.topics = Collections.singletonList("topic_speed");
  14. this.shutdown = new AtomicBoolean(false);
  15. this.shutdownLatch = new CountDownLatch(1);
  16. }
  17. public abstract void process(ResultBean result);
  18. public void pollData() throws SQLException {
  19. try {
  20. consumer.subscribe(topics);
  21. while (!shutdown.get()) {
  22. ConsumerRecords<ResultBean> records = consumer.poll(Duration.ofMillis(100));
  23. for (ResultBean record : records) {
  24. process(record);
  25. }
  26. }
  27. consumer.unsubscribe();
  28. } finally {
  29. consumer.close();
  30. shutdownLatch.countDown();
  31. }
  32. }
  33. public void shutdown() throws InterruptedException {
  34. shutdown.set(true);
  35. shutdownLatch.await();
  36. }
  37. public static class ResultDeserializer extends ReferenceDeserializer<ResultBean> {
  38. }
  39. public static class ResultBean {
  40. private Timestamp ts;
  41. private int speed;
  42. public Timestamp getTs() {
  43. return ts;
  44. }
  45. public void setTs(Timestamp ts) {
  46. this.ts = ts;
  47. }
  48. public int getSpeed() {
  49. return speed;
  50. }
  51. public void setSpeed(int speed) {
  52. this.speed = speed;
  53. }
  54. }
  55. }

Use with connection pool

HikariCP

Example usage is as follows.

  1. public static void main(String[] args) throws SQLException {
  2. HikariConfig config = new HikariConfig();
  3. // jdbc properties
  4. config.setJdbcUrl("jdbc:TAOS://127.0.0.1:6030/log");
  5. config.setUsername("root");
  6. config.setPassword("taosdata");
  7. // connection pool configurations
  8. config.setMinimumIdle(10); //minimum number of idle connection
  9. config.setMaximumPoolSize(10); //maximum number of connection in the pool
  10. config.setConnectionTimeout(30000); //maximum wait milliseconds for get connection from pool
  11. config.setMaxLifetime(0); // maximum life time for each connection
  12. config.setIdleTimeout(0); // max idle time for recycle idle connection
  13. config.setConnectionTestQuery("select server_status()"); //validation query
  14. HikariDataSource ds = new HikariDataSource(config); //create datasource
  15. Connection connection = ds.getConnection(); // get connection
  16. Statement statement = connection.createStatement(); // get statement
  17. //query or insert
  18. // ...
  19. connection.close(); // put back to connection pool
  20. }

getConnection(), you need to call the close() method after you finish using it. It doesn’t close the connection. It just puts it back into the connection pool. For more questions about using HikariCP, please see the official instructions.

Druid

Example usage is as follows.

  1. public static void main(String[] args) throws Exception {
  2. DruidDataSource dataSource = new DruidDataSource();
  3. // jdbc properties
  4. dataSource.setDriverClassName("com.taosdata.jdbc.TSDBDriver");
  5. dataSource.setUrl(url);
  6. dataSource.setUsername("root");
  7. dataSource.setPassword("taosdata");
  8. // pool configurations
  9. dataSource.setInitialSize(10);
  10. dataSource.setMinIdle(10);
  11. dataSource.setMaxActive(10);
  12. dataSource.setMaxWait(30000);
  13. dataSource.setValidationQuery("select server_status()");
  14. Connection connection = dataSource.getConnection(); // get connection
  15. Statement statement = connection.createStatement(); // get statement
  16. //query or insert
  17. // ...
  18. connection.close(); // put back to connection pool
  19. }

For more questions about using druid, please see Official Instructions.

More sample programs

The source code of the sample application is under TDengine/examples/JDBC:

  • JDBCDemo: JDBC sample source code.
  • JDBCConnectorChecker: JDBC installation checker source and jar package.
  • connectionPools: using taos-jdbcdriver in connection pools such as HikariCP, Druid, dbcp, c3p0, etc.
  • SpringJdbcTemplate: using taos-jdbcdriver in Spring JdbcTemplate.
  • mybatisplus-demo: using taos-jdbcdriver in Springboot + Mybatis.

JDBC example

Recent update logs

taos-jdbcdriver versionmajor changes
3.0.3fix timestamp resolution error for REST connection in jdk17+ version
3.0.1 - 3.0.2fix the resultSet data is parsed incorrectly sometimes. 3.0.1 is compiled on JDK 11, you are advised to use 3.0.2 in the JDK 8 environment
3.0.0Support for TDengine 3.0
2.0.42fix wasNull interface return value in WebSocket connection
2.0.41fix decode method of username and password in REST connection
2.0.39 - 2.0.40Add REST connection/request timeout parameters
2.0.38JDBC REST connections add bulk pull function
2.0.37Support json tags
2.0.36Support schemaless writing

Frequently Asked Questions

  1. Why is there no performance improvement when using Statement’s addBatch() and executeBatch() to perform batch data writing/update?

    Cause: In TDengine’s JDBC implementation, SQL statements submitted by addBatch() method are executed sequentially in the order they are added, which does not reduce the number of interactions with the server and does not bring performance improvement.

    Solution: 1. splice multiple values in a single insert statement; 2. use multi-threaded concurrent insertion; 3. use parameter-bound writing

  2. java.lang.UnsatisfiedLinkError: no taos in java.library.path

    Cause: The program did not find the dependent native library taos.

    Solution: On Windows you can copy C:\TDengine\driver\taos.dll to the C:\Windows\System32 directory, on Linux the following soft link will be created ln -s /usr/local/taos/driver/libtaos.so.x.x.x.x /usr/lib/libtaos.so will work, on macOS the lib soft link will be /usr/local/lib/libtaos.dylib.

  3. java.lang.UnsatisfiedLinkError: taos.dll Can’t load AMD 64 bit on a IA 32-bit platform

    Cause: Currently, TDengine only supports 64-bit JDK.

    Solution: Reinstall the 64-bit JDK.

  4. java.lang.NoSuchMethodError: setByteArray

    Cause: taos-jbdcdriver 3.* only supports TDengine 3.0 and later.

    Solution: Use taos-jdbcdriver 2. with your TDengine 2. deployment.

  5. java.lang.NoSuchMethodError: java.nio.ByteBuffer.position(I)Ljava/nio/ByteBuffer; … taos-jdbcdriver-3.0.1.jar

Cause:taos-jdbcdriver 3.0.1 is compiled on JDK 11.

Solution: Use taos-jdbcdriver 3.0.2.

For additional troubleshooting, see FAQ.

API Reference

taos-jdbcdriver doc