Updated on 2024-08-10 GMT+08:00

Java Example Code

Description

Run the IoTDB SQL statement in JDBC connection mode.

Sample Code

The following code snippets are used as an example. For complete codes, see the com.huawei.bigdata.iotdb.JDBCExample class.

jdbc url includes the IP address, port number, username, and password of the node where the IoTDBServer to be connected is located.

  • On FusionInsight Manager, choose Cluster > Services > IoTDB > Instance to view the IP address of the node where the IoTDBServer to be connected is located.
  • To obtain the RPC port number, log in to FusionInsight Manager, choose Cluster > Services > IoTDB. Click Configuration, click All Configurations, and search for IOTDB_SERVER_RPC_PORT.
  • In normal mode, IoTDB has a default user root after initial installation. To obtain the password, see User Account List. This user is an administrator and has all permissions, which cannot be assigned, revoked, or deleted.
  • You need to set the username and password for authentication in the local environment variables. You are advised to store the username and password in ciphertext and decrypt them upon using.
    • Authentication username is the username for accessing IoTDB.
    • Password is the password for accessing IoTDB.
  private static final String IOTDB_SSL_ENABLE = "false";//To obtain the value, log in to FusionInsight Manager, choose Cluster > Services > IoTDB, click Configurations, search for SSL in the search box, and view the value of SSL_ENABLE.
public static void main(String[] args) throws ClassNotFoundException, SQLException {
    Class.forName("org.apache.iotdb.jdbc.IoTDBDriver");
    // set iotdb_ssl_enable
    System.setProperty("iotdb_ssl_enable", IOTDB_SSL_ENABLE);
    if ("true".equals(IOTDB_SSL_ENABLE)) {  
      // set truststore.jks path  
      System.setProperty("iotdb_ssl_truststore", "truststore file path");
    }
    try (Connection connection =
            DriverManager.getConnection ("jdbc:iotdb://127.0.0.1:22260/," "Authentication username","Password");
        Statement statement = connection.createStatement()) {

      // set JDBC fetchSize
      statement.setFetchSize(10000);
      for (int i = 0; i <= 100; i++) {
        statement.addBatch(prepareInsertStatment(i));
      }
      statement.executeBatch();
      statement.clearBatch();

      ResultSet resultSet = statement.executeQuery("select ** from root where time <= 10");
      outputResult(resultSet);
      resultSet = statement.executeQuery("select count(**) from root");
      outputResult(resultSet);
      resultSet =
          statement.executeQuery(
              "select count(**) from root where time >= 1 and time <= 100 group by ([0, 100), 20ms, 20ms)");
      outputResult(resultSet);
    } catch (IoTDBSQLException e) {
      System.out.println(e.getMessage());
    }
  }