Programming - JDBC

Usage

Dependencies

  • JDK >= 1.8
  • Maven >= 3.1

How to package only jdbc project

In root directory:

  1. mvn clean package -pl jdbc -am -Dmaven.test.skip=true

How to install in local maven repository

In root directory:

  1. mvn clean install -pl jdbc -am -Dmaven.test.skip=true

Using IoTDB JDBC with Maven

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.apache.iotdb</groupId>
  4. <artifactId>iotdb-jdbc</artifactId>
  5. <version>0.9.3</version>
  6. </dependency>
  7. </dependencies>

Examples

This chapter provides an example of how to open a database connection, execute a SQL query, and display the results.

Requires that you include the packages containing the JDBC classes needed for database programming.

NOTE: For faster insertion, the insertBatch() in Session is recommended.

  1. import java.sql.*;
  2. import org.apache.iotdb.jdbc.IoTDBSQLException;
  3. public class JDBCExample {
  4. /**
  5. * Before executing a SQL statement with a Statement object, you need to create a Statement object using the createStatement() method of the Connection object.
  6. * After creating a Statement object, you can use its execute() method to execute a SQL statement
  7. * Finally, remember to close the 'statement' and 'connection' objects by using their close() method
  8. * For statements with query results, we can use the getResultSet() method of the Statement object to get the result set.
  9. */
  10. public static void main(String[] args) throws SQLException {
  11. Connection connection = getConnection();
  12. if (connection == null) {
  13. System.out.println("get connection defeat");
  14. return;
  15. }
  16. Statement statement = connection.createStatement();
  17. //Create storage group
  18. try {
  19. statement.execute("SET STORAGE GROUP TO root.demo");
  20. }catch (IoTDBSQLException e){
  21. System.out.println(e.getMessage());
  22. }
  23. //Show storage group
  24. statement.execute("SHOW STORAGE GROUP");
  25. outputResult(statement.getResultSet());
  26. //Create time series
  27. //Different data type has different encoding methods. Here use INT32 as an example
  28. try {
  29. statement.execute("CREATE TIMESERIES root.demo.s0 WITH DATATYPE=INT32,ENCODING=RLE;");
  30. }catch (IoTDBSQLException e){
  31. System.out.println(e.getMessage());
  32. }
  33. //Show time series
  34. statement.execute("SHOW TIMESERIES root.demo");
  35. outputResult(statement.getResultSet());
  36. //Show devices
  37. statement.execute("SHOW DEVICES");
  38. outputResult(statement.getResultSet());
  39. //Count time series
  40. statement.execute("COUNT TIMESERIES root");
  41. outputResult(statement.getResultSet());
  42. //Count nodes at the given level
  43. statement.execute("COUNT NODES root LEVEL=3");
  44. outputResult(statement.getResultSet());
  45. //Count timeseries group by each node at the given level
  46. statement.execute("COUNT TIMESERIES root GROUP BY LEVEL=3");
  47. outputResult(statement.getResultSet());
  48. //Execute insert statements in batch
  49. statement.addBatch("insert into root.demo(timestamp,s0) values(1,1);");
  50. statement.addBatch("insert into root.demo(timestamp,s0) values(1,1);");
  51. statement.addBatch("insert into root.demo(timestamp,s0) values(2,15);");
  52. statement.addBatch("insert into root.demo(timestamp,s0) values(2,17);");
  53. statement.addBatch("insert into root.demo(timestamp,s0) values(4,12);");
  54. statement.executeBatch();
  55. statement.clearBatch();
  56. //Full query statement
  57. String sql = "select * from root.demo";
  58. ResultSet resultSet = statement.executeQuery(sql);
  59. System.out.println("sql: " + sql);
  60. outputResult(resultSet);
  61. //Exact query statement
  62. sql = "select s0 from root.demo where time = 4;";
  63. resultSet= statement.executeQuery(sql);
  64. System.out.println("sql: " + sql);
  65. outputResult(resultSet);
  66. //Time range query
  67. sql = "select s0 from root.demo where time >= 2 and time < 5;";
  68. resultSet = statement.executeQuery(sql);
  69. System.out.println("sql: " + sql);
  70. outputResult(resultSet);
  71. //Aggregate query
  72. sql = "select count(s0) from root.demo;";
  73. resultSet = statement.executeQuery(sql);
  74. System.out.println("sql: " + sql);
  75. outputResult(resultSet);
  76. //Delete time series
  77. statement.execute("delete timeseries root.demo.s0");
  78. //close connection
  79. statement.close();
  80. connection.close();
  81. }
  82. public static Connection getConnection() {
  83. // JDBC driver name and database URL
  84. String driver = "org.apache.iotdb.jdbc.IoTDBDriver";
  85. String url = "jdbc:iotdb://127.0.0.1:6667/";
  86. // Database credentials
  87. String username = "root";
  88. String password = "root";
  89. Connection connection = null;
  90. try {
  91. Class.forName(driver);
  92. connection = DriverManager.getConnection(url, username, password);
  93. } catch (ClassNotFoundException e) {
  94. e.printStackTrace();
  95. } catch (SQLException e) {
  96. e.printStackTrace();
  97. }
  98. return connection;
  99. }
  100. /**
  101. * This is an example of outputting the results in the ResultSet
  102. */
  103. private static void outputResult(ResultSet resultSet) throws SQLException {
  104. if (resultSet != null) {
  105. System.out.println("--------------------------");
  106. final ResultSetMetaData metaData = resultSet.getMetaData();
  107. final int columnCount = metaData.getColumnCount();
  108. for (int i = 0; i < columnCount; i++) {
  109. System.out.print(metaData.getColumnLabel(i + 1) + " ");
  110. }
  111. System.out.println();
  112. while (resultSet.next()) {
  113. for (int i = 1; ; i++) {
  114. System.out.print(resultSet.getString(i));
  115. if (i < columnCount) {
  116. System.out.print(", ");
  117. } else {
  118. System.out.println();
  119. break;
  120. }
  121. }
  122. }
  123. System.out.println("--------------------------\n");
  124. }
  125. }
  126. }

Status Code

Status Code is introduced in the latest version. For example, as IoTDB requires registering the time series first before writing data, a kind of solution is:

  1. try {
  2. writeData();
  3. } catch (SQLException e) {
  4. // the most case is that the time series does not exist
  5. if (e.getMessage().contains("exist")) {
  6. //However, using the content of the error message is not so efficient
  7. registerTimeSeries();
  8. //write data once again
  9. writeData();
  10. }
  11. }

With Status Code, instead of writing codes like if (e.getErrorMessage().contains("exist")), we can simply use e.getErrorCode() == TSStatusCode.TIME_SERIES_NOT_EXIST_ERROR.getStatusCode().

Here is a list of Status Code and related message:

Status CodeStatus TypeMeanings
200SUCCESS_STATUS
201STILL_EXECUTING_STATUS
202INVALID_HANDLE_STATUS
300TIMESERIES_ALREADY_EXIST_ERRORTimeseries already exists
301TIMESERIES_NOT_EXIST_ERRORTimeseries does not exist
302UNSUPPORTED_FETCH_METADATA_OPERATION_ERRORUnsupported fetch metadata operation
303METADATA_ERRORMeet error when dealing with metadata
304CHECK_FILE_LEVEL_ERRORMeet error while checking file level
305OUT_OF_TTL_ERRORInsertion time is less than TTL time bound
306CONFIG_ADJUSTERIoTDB system load is too large
307MERGE_ERRORMeet error while merging
308SYSTEM_CHECK_ERRORMeet error while system checking
309SYNC_DEVICE_OWNER_CONFLICT_ERRORSync device owners conflict
310SYNC_CONNECTION_EXCEPTIONMeet error while sync connecting
311STORAGE_GROUP_PROCESSOR_ERRORStorage group processor related error
312STORAGE_GROUP_ERRORStorage group related error
313STORAGE_ENGINE_ERRORStorage engine related error
400EXECUTE_STATEMENT_ERRORExecute statement error
401SQL_PARSE_ERRORMeet error while parsing SQL
402GENERATE_TIME_ZONE_ERRORMeet error while generating time zone
403SET_TIME_ZONE_ERRORMeet error while setting time zone
404NOT_STORAGE_GROUP_ERROROperating object is not a storage group
405QUERY_NOT_ALLOWEDQuery statements are not allowed error
406AST_FORMAT_ERRORAST format related error
407LOGICAL_OPERATOR_ERRORLogical operator related error
408LOGICAL_OPTIMIZE_ERRORLogical optimize related error
409UNSUPPORTED_FILL_TYPE_ERRORUnsupported fill type related error
410PATH_ERRORPath related error
500INTERNAL_SERVER_ERRORInternal server error
501CLOSE_OPERATION_ERRORMeet error in close operation
502READ_ONLY_SYSTEM_ERROROperating system is read only
503DISK_SPACE_INSUFFICIENT_ERRORDisk space is insufficient
504START_UP_ERRORMeet error while starting up
600WRONG_LOGIN_PASSWORD_ERRORUsername or password is wrong
601NOT_LOGIN_ERRORHas not logged in
602NO_PERMISSION_ERRORNo permissions for this operation
603UNINITIALIZED_AUTH_ERRORUninitialized authorizer

All exceptions are refactored in latest version by extracting uniform message into exception classes. Different error codes are added to all exceptions. When an exception is caught and a higher-level exception is thrown, the error code will keep and pass so that users will know the detailed error reason. A base exception class “ProcessException” is also added to be extended by all exceptions.