From 4468951b045d2b9c16320252a8591f42bb96038c Mon Sep 17 00:00:00 2001 From: W1y1r <2730956796@qq.com> Date: Thu, 27 Feb 2025 09:51:03 +0800 Subject: [PATCH] Maven modifications in open-source Java and JDBC --- src/.vuepress/sidebar/V2.0.x/en-Table.ts | 4 +- src/.vuepress/sidebar/V2.0.x/zh-Table.ts | 4 +- .../sidebar_timecho/V2.0.x/en-Table.ts | 4 +- .../sidebar_timecho/V2.0.x/zh-Table.ts | 4 +- .../Table/API/Programming-JDBC_apache.md | 187 ++++ ...ng-JDBC.md => Programming-JDBC_timecho.md} | 0 .../API/Programming-Java-Native-API_apache.md | 610 +++++++++++++ ...=> Programming-Java-Native-API_timecho.md} | 0 .../Table/QuickStart/QuickStart_apache.md | 2 +- .../Table/QuickStart/QuickStart_timecho.md | 2 +- .../API/Programming-JDBC_apache.md | 187 ++++ ...ng-JDBC.md => Programming-JDBC_timecho.md} | 0 .../API/Programming-Java-Native-API_apache.md | 610 +++++++++++++ ...=> Programming-Java-Native-API_timecho.md} | 0 .../QuickStart/QuickStart_apache.md | 2 +- .../QuickStart/QuickStart_timecho.md | 2 +- .../Table/API/Programming-JDBC_apache.md | 191 ++++ ...ng-JDBC.md => Programming-JDBC_timecho.md} | 0 .../API/Programming-Java-Native-API_apache.md | 860 ++++++++++++++++++ ...=> Programming-Java-Native-API_timecho.md} | 0 .../Table/QuickStart/QuickStart_apache.md | 2 +- .../Table/QuickStart/QuickStart_timecho.md | 2 +- .../API/Programming-JDBC_apache.md | 191 ++++ ...ng-JDBC.md => Programming-JDBC_timecho.md} | 0 .../API/Programming-Java-Native-API_apache.md | 860 ++++++++++++++++++ ...=> Programming-Java-Native-API_timecho.md} | 0 .../QuickStart/QuickStart_apache.md | 2 +- .../QuickStart/QuickStart_timecho.md | 2 +- 28 files changed, 3712 insertions(+), 16 deletions(-) create mode 100644 src/UserGuide/Master/Table/API/Programming-JDBC_apache.md rename src/UserGuide/Master/Table/API/{Programming-JDBC.md => Programming-JDBC_timecho.md} (100%) create mode 100644 src/UserGuide/Master/Table/API/Programming-Java-Native-API_apache.md rename src/UserGuide/Master/Table/API/{Programming-Java-Native-API.md => Programming-Java-Native-API_timecho.md} (100%) create mode 100644 src/UserGuide/latest-Table/API/Programming-JDBC_apache.md rename src/UserGuide/latest-Table/API/{Programming-JDBC.md => Programming-JDBC_timecho.md} (100%) create mode 100644 src/UserGuide/latest-Table/API/Programming-Java-Native-API_apache.md rename src/UserGuide/latest-Table/API/{Programming-Java-Native-API.md => Programming-Java-Native-API_timecho.md} (100%) create mode 100644 src/zh/UserGuide/Master/Table/API/Programming-JDBC_apache.md rename src/zh/UserGuide/Master/Table/API/{Programming-JDBC.md => Programming-JDBC_timecho.md} (100%) create mode 100644 src/zh/UserGuide/Master/Table/API/Programming-Java-Native-API_apache.md rename src/zh/UserGuide/Master/Table/API/{Programming-Java-Native-API.md => Programming-Java-Native-API_timecho.md} (100%) create mode 100644 src/zh/UserGuide/latest-Table/API/Programming-JDBC_apache.md rename src/zh/UserGuide/latest-Table/API/{Programming-JDBC.md => Programming-JDBC_timecho.md} (100%) create mode 100644 src/zh/UserGuide/latest-Table/API/Programming-Java-Native-API_apache.md rename src/zh/UserGuide/latest-Table/API/{Programming-Java-Native-API.md => Programming-Java-Native-API_timecho.md} (100%) diff --git a/src/.vuepress/sidebar/V2.0.x/en-Table.ts b/src/.vuepress/sidebar/V2.0.x/en-Table.ts index d9f84fb03..6a156575f 100644 --- a/src/.vuepress/sidebar/V2.0.x/en-Table.ts +++ b/src/.vuepress/sidebar/V2.0.x/en-Table.ts @@ -123,9 +123,9 @@ export const enSidebar = { collapsible: true, prefix: 'API/', children: [ - { text: 'Java Native API', link: 'Programming-Java-Native-API' }, + { text: 'Java Native API', link: 'Programming-Java-Native-API_apache' }, { text: 'Python Native API', link: 'Programming-Python-Native-API' }, - { text: 'JDBC', link: 'Programming-JDBC' }, + { text: 'JDBC', link: 'Programming-JDBC_apache' }, { text: 'RESTAPI V1 ', link: 'RestServiceV1' }, ], }, diff --git a/src/.vuepress/sidebar/V2.0.x/zh-Table.ts b/src/.vuepress/sidebar/V2.0.x/zh-Table.ts index 71045c152..789bd14f2 100644 --- a/src/.vuepress/sidebar/V2.0.x/zh-Table.ts +++ b/src/.vuepress/sidebar/V2.0.x/zh-Table.ts @@ -111,9 +111,9 @@ export const zhSidebar = { collapsible: true, prefix: 'API/', children: [ - { text: 'Java原生接口', link: 'Programming-Java-Native-API' }, + { text: 'Java原生接口', link: 'Programming-Java-Native-API_apache' }, { text: 'Python原生接口', link: 'Programming-Python-Native-API' }, - { text: 'JDBC', link: 'Programming-JDBC' }, + { text: 'JDBC', link: 'Programming-JDBC_apache' }, { text: 'RESTAPI V1 ', link: 'RestServiceV1' }, ], }, diff --git a/src/.vuepress/sidebar_timecho/V2.0.x/en-Table.ts b/src/.vuepress/sidebar_timecho/V2.0.x/en-Table.ts index be9bd2160..6a2b1f520 100644 --- a/src/.vuepress/sidebar_timecho/V2.0.x/en-Table.ts +++ b/src/.vuepress/sidebar_timecho/V2.0.x/en-Table.ts @@ -124,9 +124,9 @@ export const enSidebar = { collapsible: true, prefix: 'API/', children: [ - { text: 'Java Native API', link: 'Programming-Java-Native-API' }, + { text: 'Java Native API', link: 'Programming-Java-Native-API_timecho' }, { text: 'Python Native API', link: 'Programming-Python-Native-API' }, - { text: 'JDBC', link: 'Programming-JDBC' }, + { text: 'JDBC', link: 'Programming-JDBC_timecho' }, { text: 'RESTAPI V1 ', link: 'RestServiceV1' }, ], }, diff --git a/src/.vuepress/sidebar_timecho/V2.0.x/zh-Table.ts b/src/.vuepress/sidebar_timecho/V2.0.x/zh-Table.ts index a67a8590e..38628b0b3 100644 --- a/src/.vuepress/sidebar_timecho/V2.0.x/zh-Table.ts +++ b/src/.vuepress/sidebar_timecho/V2.0.x/zh-Table.ts @@ -115,9 +115,9 @@ export const zhSidebar = { collapsible: true, prefix: 'API/', children: [ - { text: 'Java原生接口', link: 'Programming-Java-Native-API' }, + { text: 'Java原生接口', link: 'Programming-Java-Native-API_timecho' }, { text: 'Python原生接口', link: 'Programming-Python-Native-API' }, - { text: 'JDBC', link: 'Programming-JDBC' }, + { text: 'JDBC', link: 'Programming-JDBC_timecho' }, { text: 'RESTAPI V1 ', link: 'RestServiceV1' }, ], }, diff --git a/src/UserGuide/Master/Table/API/Programming-JDBC_apache.md b/src/UserGuide/Master/Table/API/Programming-JDBC_apache.md new file mode 100644 index 000000000..13c16fe39 --- /dev/null +++ b/src/UserGuide/Master/Table/API/Programming-JDBC_apache.md @@ -0,0 +1,187 @@ + + +The IoTDB JDBC provides a standardized way to interact with the IoTDB database, allowing users to execute SQL statements from Java programs for managing databases and time-series data. It supports operations such as connecting to the database, creating, querying, updating, and deleting data, as well as batch insertion and querying of time-series data. + +**Note:** The current JDBC implementation is designed primarily for integration with third-party tools. High-performance writing **may not be achieved** when using JDBC for insert operations. For Java applications, it is recommended to use the **JAVA Native API** for optimal performance. + +## Prerequisites + +### **Environment Requirements** + +- **JDK:** Version 1.8 or higher +- **Maven:** Version 3.6 or higher + +### **Adding Maven Dependencies** + +Add the following dependency to your Maven `pom.xml` file: + +```XML + + + org.apache.iotdb + iotdb-jdbc + 2.0.1-beta + + +``` + +## Read and Write Operations + +**Write Operations:** Perform database operations such as inserting data, creating databases, and creating time-series using the `execute` method. + +**Read Operations:** Execute queries using the `executeQuery` method and retrieve results via the `ResultSet` object. + +### Method Overview + +| **Method Name** | **Description** | **Parameters** | **Return Value** | +| ------------------------------------------------------------ | ----------------------------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------- | +| Class.forName(String driver) | Loads the JDBC driver class | `driver`: Name of the JDBC driver class | `Class`: Loaded class object | +| DriverManager.getConnection(String url, String username, String password) | Establishes a database connection | `url`: Database URL `username`: Username `password`: Password | `Connection`: Database connection object | +| Connection.createStatement() | Creates a `Statement` object for executing SQL statements | None | `Statement`: SQL execution object | +| Statement.execute(String sql) | Executes a non-query SQL statement | `sql`: SQL statement to execute | `boolean`: Indicates if a `ResultSet` is returned | +| Statement.executeQuery(String sql) | Executes a query SQL statement and retrieves the result set | `sql`: SQL query statement | `ResultSet`: Query result set | +| ResultSet.getMetaData() | Retrieves metadata of the result set | None | `ResultSetMetaData`: Metadata object | +| ResultSet.next() | Moves to the next row in the result set | None | `boolean`: Whether the move was successful | +| ResultSet.getString(int columnIndex) | Retrieves the string value of a specified column | `columnIndex`: Column index (starting from 1) | `String`: Column value | + +## Sample Code + +**Note:** When using the Table Model, you must specify the `sql_dialect` parameter as `table` in the URL. Example: + +```Java +String url = "jdbc:iotdb://127.0.0.1:6667?sql_dialect=table"; +``` + +You can find the full example code at [GitHub Repository](https://github.com/apache/iotdb/blob/master/example/jdbc/src/main/java/org/apache/iotdb/TableModelJDBCExample.java). + +Here is an excerpt of the sample code: + +```Java +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb; + +import org.apache.iotdb.jdbc.IoTDBSQLException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; + +public class TableModelJDBCExample { + + private static final Logger LOGGER = LoggerFactory.getLogger(TableModelJDBCExample.class); + + public static void main(String[] args) throws ClassNotFoundException, SQLException { + Class.forName("org.apache.iotdb.jdbc.IoTDBDriver"); + + // don't specify database in url + try (Connection connection = + DriverManager.getConnection( + "jdbc:iotdb://127.0.0.1:6667?sql_dialect=table", "root", "root"); + Statement statement = connection.createStatement()) { + + statement.execute("CREATE DATABASE test1"); + statement.execute("CREATE DATABASE test2"); + + statement.execute("use test2"); + + // or use full qualified table name + statement.execute( + "create table test1.table1(region_id STRING ID, plant_id STRING ID, device_id STRING ID, model STRING ATTRIBUTE, temperature FLOAT MEASUREMENT, humidity DOUBLE MEASUREMENT) with (TTL=3600000)"); + + statement.execute( + "create table table2(region_id STRING ID, plant_id STRING ID, color STRING ATTRIBUTE, temperature FLOAT MEASUREMENT, speed DOUBLE MEASUREMENT) with (TTL=6600000)"); + + // show tables from current database + try (ResultSet resultSet = statement.executeQuery("SHOW TABLES")) { + ResultSetMetaData metaData = resultSet.getMetaData(); + System.out.println(metaData.getColumnCount()); + while (resultSet.next()) { + System.out.println(resultSet.getString(1) + ", " + resultSet.getInt(2)); + } + } + + // show tables by specifying another database + // using SHOW tables FROM + try (ResultSet resultSet = statement.executeQuery("SHOW TABLES FROM test1")) { + ResultSetMetaData metaData = resultSet.getMetaData(); + System.out.println(metaData.getColumnCount()); + while (resultSet.next()) { + System.out.println(resultSet.getString(1) + ", " + resultSet.getInt(2)); + } + } + + } catch (IoTDBSQLException e) { + LOGGER.error("IoTDB Jdbc example error", e); + } + + // specify database in url + try (Connection connection = + DriverManager.getConnection( + "jdbc:iotdb://127.0.0.1:6667/test1?sql_dialect=table", "root", "root"); + Statement statement = connection.createStatement()) { + // show tables from current database test1 + try (ResultSet resultSet = statement.executeQuery("SHOW TABLES")) { + ResultSetMetaData metaData = resultSet.getMetaData(); + System.out.println(metaData.getColumnCount()); + while (resultSet.next()) { + System.out.println(resultSet.getString(1) + ", " + resultSet.getInt(2)); + } + } + + // change database to test2 + statement.execute("use test2"); + + try (ResultSet resultSet = statement.executeQuery("SHOW TABLES")) { + ResultSetMetaData metaData = resultSet.getMetaData(); + System.out.println(metaData.getColumnCount()); + while (resultSet.next()) { + System.out.println(resultSet.getString(1) + ", " + resultSet.getInt(2)); + } + } + } + } +} +``` \ No newline at end of file diff --git a/src/UserGuide/Master/Table/API/Programming-JDBC.md b/src/UserGuide/Master/Table/API/Programming-JDBC_timecho.md similarity index 100% rename from src/UserGuide/Master/Table/API/Programming-JDBC.md rename to src/UserGuide/Master/Table/API/Programming-JDBC_timecho.md diff --git a/src/UserGuide/Master/Table/API/Programming-Java-Native-API_apache.md b/src/UserGuide/Master/Table/API/Programming-Java-Native-API_apache.md new file mode 100644 index 000000000..2fd8718be --- /dev/null +++ b/src/UserGuide/Master/Table/API/Programming-Java-Native-API_apache.md @@ -0,0 +1,610 @@ + + +IoTDB provides a Java native client driver and a session pool management mechanism. These tools enable developers to interact with IoTDB using object-oriented APIs, allowing time-series objects to be directly assembled and inserted into the database without constructing SQL statements. It is recommended to use the `ITableSessionPool` for multi-threaded database operations to maximize efficiency. + +## Prerequisites + +### Environment Requirements + +- **JDK**: Version 1.8 or higher +- **Maven**: Version 3.6 or higher + +### Adding Maven Dependencies + +```XML + + + org.apache.iotdb + iotdb-session + 2.0.1-beta + + +``` + +## Read and Write Operations + +### ITableSession Interface + +The `ITableSession` interface defines basic operations for interacting with IoTDB, including data insertion, query execution, and session closure. Note that this interface is **not thread-safe**. + +#### Method Overview + +| **Method Name** | **Description** | **Parameters** | **Return Value** | **Exceptions** | +| --------------------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | ---------------- | --------------------------------------------------------- | +| insert(Tablet tablet) | Inserts a `Tablet` containing time-series data into the database. | `tablet`: The `Tablet` object to be inserted. | None | `StatementExecutionException`, `IoTDBConnectionException` | +| executeNonQueryStatement(String sql) | Executes non-query SQL statements such as DDL or DML commands. | `sql`: The SQL statement to execute. | None | `StatementExecutionException`, `IoTDBConnectionException` | +| executeQueryStatement(String sql) | Executes a query SQL statement and returns a `SessionDataSet` containing the query results. | `sql`: The SQL query statement to execute. | `SessionDataSet` | `StatementExecutionException`, `IoTDBConnectionException` | +| executeQueryStatement(String sql, long timeoutInMs) | Executes a query SQL statement with a specified timeout in milliseconds. | `sql`: The SQL query statement. `timeoutInMs`: Query timeout in milliseconds. | `SessionDataSet` | `StatementExecutionException` | +| close() | Closes the session and releases resources. | None | None | IoTDBConnectionException | + +#### Sample Code + +```Java +/** + * This interface defines a session for interacting with IoTDB tables. + * It supports operations such as data insertion, executing queries, and closing the session. + * Implementations of this interface are expected to manage connections and ensure + * proper resource cleanup. + * + *

Each method may throw exceptions to indicate issues such as connection errors or + * execution failures. + * + *

Since this interface extends {@link AutoCloseable}, it is recommended to use + * try-with-resources to ensure the session is properly closed. + */ +public interface ITableSession extends AutoCloseable { + + /** + * Inserts a {@link Tablet} into the database. + * + * @param tablet the tablet containing time-series data to be inserted. + * @throws StatementExecutionException if an error occurs while executing the statement. + * @throws IoTDBConnectionException if there is an issue with the IoTDB connection. + */ + void insert(Tablet tablet) throws StatementExecutionException, IoTDBConnectionException; + + /** + * Executes a non-query SQL statement, such as a DDL or DML command. + * + * @param sql the SQL statement to execute. + * @throws IoTDBConnectionException if there is an issue with the IoTDB connection. + * @throws StatementExecutionException if an error occurs while executing the statement. + */ + void executeNonQueryStatement(String sql) throws IoTDBConnectionException, StatementExecutionException; + + /** + * Executes a query SQL statement and returns the result set. + * + * @param sql the SQL query statement to execute. + * @return a {@link SessionDataSet} containing the query results. + * @throws StatementExecutionException if an error occurs while executing the statement. + * @throws IoTDBConnectionException if there is an issue with the IoTDB connection. + */ + SessionDataSet executeQueryStatement(String sql) + throws StatementExecutionException, IoTDBConnectionException; + + /** + * Executes a query SQL statement with a specified timeout and returns the result set. + * + * @param sql the SQL query statement to execute. + * @param timeoutInMs the timeout duration in milliseconds for the query execution. + * @return a {@link SessionDataSet} containing the query results. + * @throws StatementExecutionException if an error occurs while executing the statement. + * @throws IoTDBConnectionException if there is an issue with the IoTDB connection. + */ + SessionDataSet executeQueryStatement(String sql, long timeoutInMs) + throws StatementExecutionException, IoTDBConnectionException; + + /** + * Closes the session, releasing any held resources. + * + * @throws IoTDBConnectionException if there is an issue with closing the IoTDB connection. + */ + @Override + void close() throws IoTDBConnectionException; +} +``` + +### TableSessionBuilder Class + +The `TableSessionBuilder` class is a builder for configuring and creating instances of the `ITableSession` interface. It allows developers to set connection parameters, query parameters, and security features. + +#### Parameter Configuration + +| **Parameter** | **Description** | **Default Value** | +|-----------------------------------------------------| ------------------------------------------------------------ | ------------------------------------------------- | +| nodeUrls(List\ nodeUrls) | Sets the list of IoTDB cluster node URLs. | `Collections.singletonList("``localhost:6667``")` | +| username(String username) | Sets the username for the connection. | `"root"` | +| password(String password) | Sets the password for the connection. | `"root"` | +| database(String database) | Sets the target database name. | `null` | +| queryTimeoutInMs(long queryTimeoutInMs) | Sets the query timeout in milliseconds. | `60000` (1 minute) | +| fetchSize(int fetchSize) | Sets the fetch size for query results. | `5000` | +| zoneId(ZoneId zoneId) | Sets the timezone-related `ZoneId`. | `ZoneId.systemDefault()` | +| thriftDefaultBufferSize(int thriftDefaultBufferSize) | Sets the default buffer size for the Thrift client (in bytes). | `1024`(1KB) | +| thriftMaxFrameSize(int thriftMaxFrameSize) | Sets the maximum frame size for the Thrift client (in bytes). | `64 * 1024 * 1024`(64MB) | +| enableRedirection(boolean enableRedirection) | Enables or disables redirection for cluster nodes. | `true` | +| enableAutoFetch(boolean enableAutoFetch) | Enables or disables automatic fetching of available DataNodes. | `true` | +| maxRetryCount(int maxRetryCount) | Sets the maximum number of connection retry attempts. | `60` | +| retryIntervalInMs(long retryIntervalInMs) | Sets the interval between retry attempts (in milliseconds). | `500`(500 millisesonds) | +| useSSL(boolean useSSL) | Enables or disables SSL for secure connections. | `false` | +| trustStore(String keyStore) | Sets the path to the trust store for SSL connections. | `null` | +| trustStorePwd(String keyStorePwd) | Sets the password for the SSL trust store. | `null` | +| enableCompression(boolean enableCompression) | Enables or disables RPC compression for the connection. | `false` | +| connectionTimeoutInMs(int connectionTimeoutInMs) | Sets the connection timeout in milliseconds. | `0` (no timeout) | + +#### Sample Code + +```Java +/** + * A builder class for constructing instances of {@link ITableSession}. + * + *

This builder provides a fluent API for configuring various options such as connection + * settings, query parameters, and security features. + * + *

All configurations have reasonable default values, which can be overridden as needed. + */ +public class TableSessionBuilder { + + /** + * Builds and returns a configured {@link ITableSession} instance. + * + * @return a fully configured {@link ITableSession}. + * @throws IoTDBConnectionException if an error occurs while establishing the connection. + */ + public ITableSession build() throws IoTDBConnectionException; + + /** + * Sets the list of node URLs for the IoTDB cluster. + * + * @param nodeUrls a list of node URLs. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue Collection.singletonList("localhost:6667") + */ + public TableSessionBuilder nodeUrls(List nodeUrls); + + /** + * Sets the username for the connection. + * + * @param username the username. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue "root" + */ + public TableSessionBuilder username(String username); + + /** + * Sets the password for the connection. + * + * @param password the password. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue "root" + */ + public TableSessionBuilder password(String password); + + /** + * Sets the target database name. + * + * @param database the database name. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue null + */ + public TableSessionBuilder database(String database); + + /** + * Sets the query timeout in milliseconds. + * + * @param queryTimeoutInMs the query timeout in milliseconds. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue 60000 (1 minute) + */ + public TableSessionBuilder queryTimeoutInMs(long queryTimeoutInMs); + + /** + * Sets the fetch size for query results. + * + * @param fetchSize the fetch size. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue 5000 + */ + public TableSessionBuilder fetchSize(int fetchSize); + + /** + * Sets the {@link ZoneId} for timezone-related operations. + * + * @param zoneId the {@link ZoneId}. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue ZoneId.systemDefault() + */ + public TableSessionBuilder zoneId(ZoneId zoneId); + + /** + * Sets the default init buffer size for the Thrift client. + * + * @param thriftDefaultBufferSize the buffer size in bytes. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue 1024 (1 KB) + */ + public TableSessionBuilder thriftDefaultBufferSize(int thriftDefaultBufferSize); + + /** + * Sets the maximum frame size for the Thrift client. + * + * @param thriftMaxFrameSize the maximum frame size in bytes. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue 64 * 1024 * 1024 (64 MB) + */ + public TableSessionBuilder thriftMaxFrameSize(int thriftMaxFrameSize); + + /** + * Enables or disables redirection for cluster nodes. + * + * @param enableRedirection whether to enable redirection. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue true + */ + public TableSessionBuilder enableRedirection(boolean enableRedirection); + + /** + * Enables or disables automatic fetching of available DataNodes. + * + * @param enableAutoFetch whether to enable automatic fetching. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue true + */ + public TableSessionBuilder enableAutoFetch(boolean enableAutoFetch); + + /** + * Sets the maximum number of retries for connection attempts. + * + * @param maxRetryCount the maximum retry count. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue 60 + */ + public TableSessionBuilder maxRetryCount(int maxRetryCount); + + /** + * Sets the interval between retries in milliseconds. + * + * @param retryIntervalInMs the interval in milliseconds. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue 500 milliseconds + */ + public TableSessionBuilder retryIntervalInMs(long retryIntervalInMs); + + /** + * Enables or disables SSL for secure connections. + * + * @param useSSL whether to enable SSL. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue false + */ + public TableSessionBuilder useSSL(boolean useSSL); + + /** + * Sets the trust store path for SSL connections. + * + * @param keyStore the trust store path. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue null + */ + public TableSessionBuilder trustStore(String keyStore); + + /** + * Sets the trust store password for SSL connections. + * + * @param keyStorePwd the trust store password. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue null + */ + public TableSessionBuilder trustStorePwd(String keyStorePwd); + + /** + * Enables or disables rpc compression for the connection. + * + * @param enableCompression whether to enable compression. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue false + */ + public TableSessionBuilder enableCompression(boolean enableCompression); + + /** + * Sets the connection timeout in milliseconds. + * + * @param connectionTimeoutInMs the connection timeout in milliseconds. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue 0 (no timeout) + */ + public TableSessionBuilder connectionTimeoutInMs(int connectionTimeoutInMs); +} +``` + +## Session Pool + +### ITableSessionPool Interface + +The `ITableSessionPool` interface manages a pool of `ITableSession` instances, enabling efficient reuse of connections and proper cleanup of resources. + +#### Method Overview + +| **Method Name** | **Description** | **Return Value** | **Exceptions** | +| --------------- | ---------------------------------------------------------- | ---------------- | -------------------------- | +| getSession() | Acquires a session from the pool for database interaction. | `ITableSession` | `IoTDBConnectionException` | +| close() | Closes the session pool and releases resources.。 | None | None | + +#### Sample Code + +```Java +/** + * This interface defines a pool for managing {@link ITableSession} instances. + * It provides methods to acquire a session from the pool and to close the pool. + * + *

The implementation should handle the lifecycle of sessions, ensuring efficient + * reuse and proper cleanup of resources. + */ +public interface ITableSessionPool { + + /** + * Acquires an {@link ITableSession} instance from the pool. + * + * @return an {@link ITableSession} instance for interacting with the IoTDB. + * @throws IoTDBConnectionException if there is an issue obtaining a session from the pool. + */ + ITableSession getSession() throws IoTDBConnectionException; + + /** + * Closes the session pool, releasing any held resources. + * + *

Once the pool is closed, no further sessions can be acquired. + */ + void close(); +} +``` + +### TableSessionPoolBuilder Class + +The `TableSessionPoolBuilder` class is a builder for configuring and creating `ITableSessionPool` instances, supporting options like connection settings and pooling behavior. + +#### Parameter Configuration + +| **Parameter** | **Description** | **Default Value** | +|---------------------------------------------------------------| ------------------------------------------------------------ | --------------------------------------------- | +| nodeUrls(List\ nodeUrls) | Sets the list of IoTDB cluster node URLs. | `Collections.singletonList("localhost:6667")` | +| maxSize(int maxSize) | Sets the maximum size of the session pool, i.e., the maximum number of sessions allowed in the pool. | `5` | +| user(String user) | Sets the username for the connection. | `"root"` | +| password(String password) | Sets the password for the connection. | `"root"` | +| database(String database) | Sets the target database name. | `"root"` | +| queryTimeoutInMs(long queryTimeoutInMs) | Sets the query timeout in milliseconds. | `60000`(1 minute) | +| fetchSize(int fetchSize) | Sets the fetch size for query results. | `5000` | +| zoneId(ZoneId zoneId) | Sets the timezone-related `ZoneId`. | `ZoneId.systemDefault()` | +| waitToGetSessionTimeoutInMs(long waitToGetSessionTimeoutInMs) | Sets the timeout duration (in milliseconds) for acquiring a session from the pool. | `30000`(30 seconds) | +| thriftDefaultBufferSize(int thriftDefaultBufferSize) | Sets the default buffer size for the Thrift client (in bytes). | `1024`(1KB) | +| thriftMaxFrameSize(int thriftMaxFrameSize) | Sets the maximum frame size for the Thrift client (in bytes). | `64 * 1024 * 1024`(64MB) | +| enableCompression(boolean enableCompression) | Enables or disables compression for the connection. | `false` | +| enableRedirection(boolean enableRedirection) | Enables or disables redirection for cluster nodes. | `true` | +| connectionTimeoutInMs(int connectionTimeoutInMs) | Sets the connection timeout in milliseconds. | `10000` (10 seconds) | +| enableAutoFetch(boolean enableAutoFetch) | Enables or disables automatic fetching of available DataNodes. | `true` | +| maxRetryCount(int maxRetryCount) | Sets the maximum number of connection retry attempts. | `60` | +| retryIntervalInMs(long retryIntervalInMs) | Sets the interval between retry attempts (in milliseconds). | `500` (500 milliseconds) | +| useSSL(boolean useSSL) | Enables or disables SSL for secure connections. | `false` | +| trustStore(String keyStore) | Sets the path to the trust store for SSL connections. | `null` | +| trustStorePwd(String keyStorePwd) | Sets the password for the SSL trust store. | `null` | + +#### Sample Code + +```Java +/** + * A builder class for constructing instances of {@link ITableSessionPool}. + * + *

This builder provides a fluent API for configuring a session pool, including + * connection settings, session parameters, and pool behavior. + * + *

All configurations have reasonable default values, which can be overridden as needed. + */ +public class TableSessionPoolBuilder { + + /** + * Builds and returns a configured {@link ITableSessionPool} instance. + * + * @return a fully configured {@link ITableSessionPool}. + */ + public ITableSessionPool build(); + + /** + * Sets the list of node URLs for the IoTDB cluster. + * + * @param nodeUrls a list of node URLs. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue Collection.singletonList("localhost:6667") + */ + public TableSessionPoolBuilder nodeUrls(List nodeUrls); + + /** + * Sets the maximum size of the session pool. + * + * @param maxSize the maximum number of sessions allowed in the pool. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue 5 + */ + public TableSessionPoolBuilder maxSize(int maxSize); + + /** + * Sets the username for the connection. + * + * @param user the username. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue "root" + */ + public TableSessionPoolBuilder user(String user); + + /** + * Sets the password for the connection. + * + * @param password the password. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue "root" + */ + public TableSessionPoolBuilder password(String password); + + /** + * Sets the target database name. + * + * @param database the database name. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue "root" + */ + public TableSessionPoolBuilder database(String database); + + /** + * Sets the query timeout in milliseconds. + * + * @param queryTimeoutInMs the query timeout in milliseconds. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue 60000 (1 minute) + */ + public TableSessionPoolBuilder queryTimeoutInMs(long queryTimeoutInMs); + + /** + * Sets the fetch size for query results. + * + * @param fetchSize the fetch size. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue 5000 + */ + public TableSessionPoolBuilder fetchSize(int fetchSize); + + /** + * Sets the {@link ZoneId} for timezone-related operations. + * + * @param zoneId the {@link ZoneId}. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue ZoneId.systemDefault() + */ + public TableSessionPoolBuilder zoneId(ZoneId zoneId); + + /** + * Sets the timeout for waiting to acquire a session from the pool. + * + * @param waitToGetSessionTimeoutInMs the timeout duration in milliseconds. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue 30000 (30 seconds) + */ + public TableSessionPoolBuilder waitToGetSessionTimeoutInMs(long waitToGetSessionTimeoutInMs); + + /** + * Sets the default buffer size for the Thrift client. + * + * @param thriftDefaultBufferSize the buffer size in bytes. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue 1024 (1 KB) + */ + public TableSessionPoolBuilder thriftDefaultBufferSize(int thriftDefaultBufferSize); + + /** + * Sets the maximum frame size for the Thrift client. + * + * @param thriftMaxFrameSize the maximum frame size in bytes. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue 64 * 1024 * 1024 (64 MB) + */ + public TableSessionPoolBuilder thriftMaxFrameSize(int thriftMaxFrameSize); + + /** + * Enables or disables compression for the connection. + * + * @param enableCompression whether to enable compression. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue false + */ + public TableSessionPoolBuilder enableCompression(boolean enableCompression); + + /** + * Enables or disables redirection for cluster nodes. + * + * @param enableRedirection whether to enable redirection. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue true + */ + public TableSessionPoolBuilder enableRedirection(boolean enableRedirection); + + /** + * Sets the connection timeout in milliseconds. + * + * @param connectionTimeoutInMs the connection timeout in milliseconds. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue 10000 (10 seconds) + */ + public TableSessionPoolBuilder connectionTimeoutInMs(int connectionTimeoutInMs); + + /** + * Enables or disables automatic fetching of available DataNodes. + * + * @param enableAutoFetch whether to enable automatic fetching. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue true + */ + public TableSessionPoolBuilder enableAutoFetch(boolean enableAutoFetch); + + /** + * Sets the maximum number of retries for connection attempts. + * + * @param maxRetryCount the maximum retry count. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue 60 + */ + public TableSessionPoolBuilder maxRetryCount(int maxRetryCount); + + /** + * Sets the interval between retries in milliseconds. + * + * @param retryIntervalInMs the interval in milliseconds. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue 500 milliseconds + */ + public TableSessionPoolBuilder retryIntervalInMs(long retryIntervalInMs); + + /** + * Enables or disables SSL for secure connections. + * + * @param useSSL whether to enable SSL. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue false + */ + public TableSessionPoolBuilder useSSL(boolean useSSL); + + /** + * Sets the trust store path for SSL connections. + * + * @param keyStore the trust store path. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue null + */ + public TableSessionPoolBuilder trustStore(String keyStore); + + /** + * Sets the trust store password for SSL connections. + * + * @param keyStorePwd the trust store password. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue null + */ + public TableSessionPoolBuilder trustStorePwd(String keyStorePwd); +} +``` \ No newline at end of file diff --git a/src/UserGuide/Master/Table/API/Programming-Java-Native-API.md b/src/UserGuide/Master/Table/API/Programming-Java-Native-API_timecho.md similarity index 100% rename from src/UserGuide/Master/Table/API/Programming-Java-Native-API.md rename to src/UserGuide/Master/Table/API/Programming-Java-Native-API_timecho.md diff --git a/src/UserGuide/Master/Table/QuickStart/QuickStart_apache.md b/src/UserGuide/Master/Table/QuickStart/QuickStart_apache.md index 2df10e79f..ea7846223 100644 --- a/src/UserGuide/Master/Table/QuickStart/QuickStart_apache.md +++ b/src/UserGuide/Master/Table/QuickStart/QuickStart_apache.md @@ -67,7 +67,7 @@ This guide will assist you in quickly installing and deploying IoTDB. You can qu - Data Synchronization: [Data Sync](../User-Manual/Data-Sync_apache.md) -6. Application Programming Interfaces (APIs): IoTDB provides various application programming interfaces (APIs) to facilitate developers' interaction with IoTDB in applications. Currently supported interfaces include [Java Native API](../API/Programming-Java-Native-API.md)、[Python Native API](../API/Programming-Python-Native-API.md)、[JDBC](../API/Programming-JDBC.md), and more. For more programming interfaces, please refer to the [Application Programming Interfaces] section on the official website. +6. Application Programming Interfaces (APIs): IoTDB provides various application programming interfaces (APIs) to facilitate developers' interaction with IoTDB in applications. Currently supported interfaces include [Java Native API](../API/Programming-Java-Native-API_apache.md)、[Python Native API](../API/Programming-Python-Native-API.md)、[JDBC](../API/Programming-JDBC_apache.md), and more. For more programming interfaces, please refer to the [Application Programming Interfaces] section on the official website. ## Want to learn more technical details? diff --git a/src/UserGuide/Master/Table/QuickStart/QuickStart_timecho.md b/src/UserGuide/Master/Table/QuickStart/QuickStart_timecho.md index 00ba1520e..3bc70e462 100644 --- a/src/UserGuide/Master/Table/QuickStart/QuickStart_timecho.md +++ b/src/UserGuide/Master/Table/QuickStart/QuickStart_timecho.md @@ -74,7 +74,7 @@ This guide will assist you in quickly installing and deploying IoTDB. You can qu - Data Synchronization: [Data Sync](../User-Manual/Data-Sync_timecho.md) -6. Application Programming Interfaces (APIs): IoTDB provides various application programming interfaces (APIs) to facilitate developers' interaction with IoTDB in applications. Currently supported interfaces include [Java Native API](../API/Programming-Java-Native-API.md)、[Python Native API](../API/Programming-Python-Native-API.md)、[JDBC](../API/Programming-JDBC.md), and more. For more programming interfaces, please refer to the [Application Programming Interfaces] section on the official website. +6. Application Programming Interfaces (APIs): IoTDB provides various application programming interfaces (APIs) to facilitate developers' interaction with IoTDB in applications. Currently supported interfaces include [Java Native API](../API/Programming-Java-Native-API_timecho.md)、[Python Native API](../API/Programming-Python-Native-API.md)、[JDBC](../API/Programming-JDBC_timecho.md), and more. For more programming interfaces, please refer to the [Application Programming Interfaces] section on the official website. ## What other convenient tools are available? diff --git a/src/UserGuide/latest-Table/API/Programming-JDBC_apache.md b/src/UserGuide/latest-Table/API/Programming-JDBC_apache.md new file mode 100644 index 000000000..13c16fe39 --- /dev/null +++ b/src/UserGuide/latest-Table/API/Programming-JDBC_apache.md @@ -0,0 +1,187 @@ + + +The IoTDB JDBC provides a standardized way to interact with the IoTDB database, allowing users to execute SQL statements from Java programs for managing databases and time-series data. It supports operations such as connecting to the database, creating, querying, updating, and deleting data, as well as batch insertion and querying of time-series data. + +**Note:** The current JDBC implementation is designed primarily for integration with third-party tools. High-performance writing **may not be achieved** when using JDBC for insert operations. For Java applications, it is recommended to use the **JAVA Native API** for optimal performance. + +## Prerequisites + +### **Environment Requirements** + +- **JDK:** Version 1.8 or higher +- **Maven:** Version 3.6 or higher + +### **Adding Maven Dependencies** + +Add the following dependency to your Maven `pom.xml` file: + +```XML + + + org.apache.iotdb + iotdb-jdbc + 2.0.1-beta + + +``` + +## Read and Write Operations + +**Write Operations:** Perform database operations such as inserting data, creating databases, and creating time-series using the `execute` method. + +**Read Operations:** Execute queries using the `executeQuery` method and retrieve results via the `ResultSet` object. + +### Method Overview + +| **Method Name** | **Description** | **Parameters** | **Return Value** | +| ------------------------------------------------------------ | ----------------------------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------- | +| Class.forName(String driver) | Loads the JDBC driver class | `driver`: Name of the JDBC driver class | `Class`: Loaded class object | +| DriverManager.getConnection(String url, String username, String password) | Establishes a database connection | `url`: Database URL `username`: Username `password`: Password | `Connection`: Database connection object | +| Connection.createStatement() | Creates a `Statement` object for executing SQL statements | None | `Statement`: SQL execution object | +| Statement.execute(String sql) | Executes a non-query SQL statement | `sql`: SQL statement to execute | `boolean`: Indicates if a `ResultSet` is returned | +| Statement.executeQuery(String sql) | Executes a query SQL statement and retrieves the result set | `sql`: SQL query statement | `ResultSet`: Query result set | +| ResultSet.getMetaData() | Retrieves metadata of the result set | None | `ResultSetMetaData`: Metadata object | +| ResultSet.next() | Moves to the next row in the result set | None | `boolean`: Whether the move was successful | +| ResultSet.getString(int columnIndex) | Retrieves the string value of a specified column | `columnIndex`: Column index (starting from 1) | `String`: Column value | + +## Sample Code + +**Note:** When using the Table Model, you must specify the `sql_dialect` parameter as `table` in the URL. Example: + +```Java +String url = "jdbc:iotdb://127.0.0.1:6667?sql_dialect=table"; +``` + +You can find the full example code at [GitHub Repository](https://github.com/apache/iotdb/blob/master/example/jdbc/src/main/java/org/apache/iotdb/TableModelJDBCExample.java). + +Here is an excerpt of the sample code: + +```Java +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb; + +import org.apache.iotdb.jdbc.IoTDBSQLException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; + +public class TableModelJDBCExample { + + private static final Logger LOGGER = LoggerFactory.getLogger(TableModelJDBCExample.class); + + public static void main(String[] args) throws ClassNotFoundException, SQLException { + Class.forName("org.apache.iotdb.jdbc.IoTDBDriver"); + + // don't specify database in url + try (Connection connection = + DriverManager.getConnection( + "jdbc:iotdb://127.0.0.1:6667?sql_dialect=table", "root", "root"); + Statement statement = connection.createStatement()) { + + statement.execute("CREATE DATABASE test1"); + statement.execute("CREATE DATABASE test2"); + + statement.execute("use test2"); + + // or use full qualified table name + statement.execute( + "create table test1.table1(region_id STRING ID, plant_id STRING ID, device_id STRING ID, model STRING ATTRIBUTE, temperature FLOAT MEASUREMENT, humidity DOUBLE MEASUREMENT) with (TTL=3600000)"); + + statement.execute( + "create table table2(region_id STRING ID, plant_id STRING ID, color STRING ATTRIBUTE, temperature FLOAT MEASUREMENT, speed DOUBLE MEASUREMENT) with (TTL=6600000)"); + + // show tables from current database + try (ResultSet resultSet = statement.executeQuery("SHOW TABLES")) { + ResultSetMetaData metaData = resultSet.getMetaData(); + System.out.println(metaData.getColumnCount()); + while (resultSet.next()) { + System.out.println(resultSet.getString(1) + ", " + resultSet.getInt(2)); + } + } + + // show tables by specifying another database + // using SHOW tables FROM + try (ResultSet resultSet = statement.executeQuery("SHOW TABLES FROM test1")) { + ResultSetMetaData metaData = resultSet.getMetaData(); + System.out.println(metaData.getColumnCount()); + while (resultSet.next()) { + System.out.println(resultSet.getString(1) + ", " + resultSet.getInt(2)); + } + } + + } catch (IoTDBSQLException e) { + LOGGER.error("IoTDB Jdbc example error", e); + } + + // specify database in url + try (Connection connection = + DriverManager.getConnection( + "jdbc:iotdb://127.0.0.1:6667/test1?sql_dialect=table", "root", "root"); + Statement statement = connection.createStatement()) { + // show tables from current database test1 + try (ResultSet resultSet = statement.executeQuery("SHOW TABLES")) { + ResultSetMetaData metaData = resultSet.getMetaData(); + System.out.println(metaData.getColumnCount()); + while (resultSet.next()) { + System.out.println(resultSet.getString(1) + ", " + resultSet.getInt(2)); + } + } + + // change database to test2 + statement.execute("use test2"); + + try (ResultSet resultSet = statement.executeQuery("SHOW TABLES")) { + ResultSetMetaData metaData = resultSet.getMetaData(); + System.out.println(metaData.getColumnCount()); + while (resultSet.next()) { + System.out.println(resultSet.getString(1) + ", " + resultSet.getInt(2)); + } + } + } + } +} +``` \ No newline at end of file diff --git a/src/UserGuide/latest-Table/API/Programming-JDBC.md b/src/UserGuide/latest-Table/API/Programming-JDBC_timecho.md similarity index 100% rename from src/UserGuide/latest-Table/API/Programming-JDBC.md rename to src/UserGuide/latest-Table/API/Programming-JDBC_timecho.md diff --git a/src/UserGuide/latest-Table/API/Programming-Java-Native-API_apache.md b/src/UserGuide/latest-Table/API/Programming-Java-Native-API_apache.md new file mode 100644 index 000000000..2fd8718be --- /dev/null +++ b/src/UserGuide/latest-Table/API/Programming-Java-Native-API_apache.md @@ -0,0 +1,610 @@ + + +IoTDB provides a Java native client driver and a session pool management mechanism. These tools enable developers to interact with IoTDB using object-oriented APIs, allowing time-series objects to be directly assembled and inserted into the database without constructing SQL statements. It is recommended to use the `ITableSessionPool` for multi-threaded database operations to maximize efficiency. + +## Prerequisites + +### Environment Requirements + +- **JDK**: Version 1.8 or higher +- **Maven**: Version 3.6 or higher + +### Adding Maven Dependencies + +```XML + + + org.apache.iotdb + iotdb-session + 2.0.1-beta + + +``` + +## Read and Write Operations + +### ITableSession Interface + +The `ITableSession` interface defines basic operations for interacting with IoTDB, including data insertion, query execution, and session closure. Note that this interface is **not thread-safe**. + +#### Method Overview + +| **Method Name** | **Description** | **Parameters** | **Return Value** | **Exceptions** | +| --------------------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | ---------------- | --------------------------------------------------------- | +| insert(Tablet tablet) | Inserts a `Tablet` containing time-series data into the database. | `tablet`: The `Tablet` object to be inserted. | None | `StatementExecutionException`, `IoTDBConnectionException` | +| executeNonQueryStatement(String sql) | Executes non-query SQL statements such as DDL or DML commands. | `sql`: The SQL statement to execute. | None | `StatementExecutionException`, `IoTDBConnectionException` | +| executeQueryStatement(String sql) | Executes a query SQL statement and returns a `SessionDataSet` containing the query results. | `sql`: The SQL query statement to execute. | `SessionDataSet` | `StatementExecutionException`, `IoTDBConnectionException` | +| executeQueryStatement(String sql, long timeoutInMs) | Executes a query SQL statement with a specified timeout in milliseconds. | `sql`: The SQL query statement. `timeoutInMs`: Query timeout in milliseconds. | `SessionDataSet` | `StatementExecutionException` | +| close() | Closes the session and releases resources. | None | None | IoTDBConnectionException | + +#### Sample Code + +```Java +/** + * This interface defines a session for interacting with IoTDB tables. + * It supports operations such as data insertion, executing queries, and closing the session. + * Implementations of this interface are expected to manage connections and ensure + * proper resource cleanup. + * + *

Each method may throw exceptions to indicate issues such as connection errors or + * execution failures. + * + *

Since this interface extends {@link AutoCloseable}, it is recommended to use + * try-with-resources to ensure the session is properly closed. + */ +public interface ITableSession extends AutoCloseable { + + /** + * Inserts a {@link Tablet} into the database. + * + * @param tablet the tablet containing time-series data to be inserted. + * @throws StatementExecutionException if an error occurs while executing the statement. + * @throws IoTDBConnectionException if there is an issue with the IoTDB connection. + */ + void insert(Tablet tablet) throws StatementExecutionException, IoTDBConnectionException; + + /** + * Executes a non-query SQL statement, such as a DDL or DML command. + * + * @param sql the SQL statement to execute. + * @throws IoTDBConnectionException if there is an issue with the IoTDB connection. + * @throws StatementExecutionException if an error occurs while executing the statement. + */ + void executeNonQueryStatement(String sql) throws IoTDBConnectionException, StatementExecutionException; + + /** + * Executes a query SQL statement and returns the result set. + * + * @param sql the SQL query statement to execute. + * @return a {@link SessionDataSet} containing the query results. + * @throws StatementExecutionException if an error occurs while executing the statement. + * @throws IoTDBConnectionException if there is an issue with the IoTDB connection. + */ + SessionDataSet executeQueryStatement(String sql) + throws StatementExecutionException, IoTDBConnectionException; + + /** + * Executes a query SQL statement with a specified timeout and returns the result set. + * + * @param sql the SQL query statement to execute. + * @param timeoutInMs the timeout duration in milliseconds for the query execution. + * @return a {@link SessionDataSet} containing the query results. + * @throws StatementExecutionException if an error occurs while executing the statement. + * @throws IoTDBConnectionException if there is an issue with the IoTDB connection. + */ + SessionDataSet executeQueryStatement(String sql, long timeoutInMs) + throws StatementExecutionException, IoTDBConnectionException; + + /** + * Closes the session, releasing any held resources. + * + * @throws IoTDBConnectionException if there is an issue with closing the IoTDB connection. + */ + @Override + void close() throws IoTDBConnectionException; +} +``` + +### TableSessionBuilder Class + +The `TableSessionBuilder` class is a builder for configuring and creating instances of the `ITableSession` interface. It allows developers to set connection parameters, query parameters, and security features. + +#### Parameter Configuration + +| **Parameter** | **Description** | **Default Value** | +|-----------------------------------------------------| ------------------------------------------------------------ | ------------------------------------------------- | +| nodeUrls(List\ nodeUrls) | Sets the list of IoTDB cluster node URLs. | `Collections.singletonList("``localhost:6667``")` | +| username(String username) | Sets the username for the connection. | `"root"` | +| password(String password) | Sets the password for the connection. | `"root"` | +| database(String database) | Sets the target database name. | `null` | +| queryTimeoutInMs(long queryTimeoutInMs) | Sets the query timeout in milliseconds. | `60000` (1 minute) | +| fetchSize(int fetchSize) | Sets the fetch size for query results. | `5000` | +| zoneId(ZoneId zoneId) | Sets the timezone-related `ZoneId`. | `ZoneId.systemDefault()` | +| thriftDefaultBufferSize(int thriftDefaultBufferSize) | Sets the default buffer size for the Thrift client (in bytes). | `1024`(1KB) | +| thriftMaxFrameSize(int thriftMaxFrameSize) | Sets the maximum frame size for the Thrift client (in bytes). | `64 * 1024 * 1024`(64MB) | +| enableRedirection(boolean enableRedirection) | Enables or disables redirection for cluster nodes. | `true` | +| enableAutoFetch(boolean enableAutoFetch) | Enables or disables automatic fetching of available DataNodes. | `true` | +| maxRetryCount(int maxRetryCount) | Sets the maximum number of connection retry attempts. | `60` | +| retryIntervalInMs(long retryIntervalInMs) | Sets the interval between retry attempts (in milliseconds). | `500`(500 millisesonds) | +| useSSL(boolean useSSL) | Enables or disables SSL for secure connections. | `false` | +| trustStore(String keyStore) | Sets the path to the trust store for SSL connections. | `null` | +| trustStorePwd(String keyStorePwd) | Sets the password for the SSL trust store. | `null` | +| enableCompression(boolean enableCompression) | Enables or disables RPC compression for the connection. | `false` | +| connectionTimeoutInMs(int connectionTimeoutInMs) | Sets the connection timeout in milliseconds. | `0` (no timeout) | + +#### Sample Code + +```Java +/** + * A builder class for constructing instances of {@link ITableSession}. + * + *

This builder provides a fluent API for configuring various options such as connection + * settings, query parameters, and security features. + * + *

All configurations have reasonable default values, which can be overridden as needed. + */ +public class TableSessionBuilder { + + /** + * Builds and returns a configured {@link ITableSession} instance. + * + * @return a fully configured {@link ITableSession}. + * @throws IoTDBConnectionException if an error occurs while establishing the connection. + */ + public ITableSession build() throws IoTDBConnectionException; + + /** + * Sets the list of node URLs for the IoTDB cluster. + * + * @param nodeUrls a list of node URLs. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue Collection.singletonList("localhost:6667") + */ + public TableSessionBuilder nodeUrls(List nodeUrls); + + /** + * Sets the username for the connection. + * + * @param username the username. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue "root" + */ + public TableSessionBuilder username(String username); + + /** + * Sets the password for the connection. + * + * @param password the password. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue "root" + */ + public TableSessionBuilder password(String password); + + /** + * Sets the target database name. + * + * @param database the database name. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue null + */ + public TableSessionBuilder database(String database); + + /** + * Sets the query timeout in milliseconds. + * + * @param queryTimeoutInMs the query timeout in milliseconds. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue 60000 (1 minute) + */ + public TableSessionBuilder queryTimeoutInMs(long queryTimeoutInMs); + + /** + * Sets the fetch size for query results. + * + * @param fetchSize the fetch size. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue 5000 + */ + public TableSessionBuilder fetchSize(int fetchSize); + + /** + * Sets the {@link ZoneId} for timezone-related operations. + * + * @param zoneId the {@link ZoneId}. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue ZoneId.systemDefault() + */ + public TableSessionBuilder zoneId(ZoneId zoneId); + + /** + * Sets the default init buffer size for the Thrift client. + * + * @param thriftDefaultBufferSize the buffer size in bytes. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue 1024 (1 KB) + */ + public TableSessionBuilder thriftDefaultBufferSize(int thriftDefaultBufferSize); + + /** + * Sets the maximum frame size for the Thrift client. + * + * @param thriftMaxFrameSize the maximum frame size in bytes. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue 64 * 1024 * 1024 (64 MB) + */ + public TableSessionBuilder thriftMaxFrameSize(int thriftMaxFrameSize); + + /** + * Enables or disables redirection for cluster nodes. + * + * @param enableRedirection whether to enable redirection. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue true + */ + public TableSessionBuilder enableRedirection(boolean enableRedirection); + + /** + * Enables or disables automatic fetching of available DataNodes. + * + * @param enableAutoFetch whether to enable automatic fetching. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue true + */ + public TableSessionBuilder enableAutoFetch(boolean enableAutoFetch); + + /** + * Sets the maximum number of retries for connection attempts. + * + * @param maxRetryCount the maximum retry count. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue 60 + */ + public TableSessionBuilder maxRetryCount(int maxRetryCount); + + /** + * Sets the interval between retries in milliseconds. + * + * @param retryIntervalInMs the interval in milliseconds. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue 500 milliseconds + */ + public TableSessionBuilder retryIntervalInMs(long retryIntervalInMs); + + /** + * Enables or disables SSL for secure connections. + * + * @param useSSL whether to enable SSL. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue false + */ + public TableSessionBuilder useSSL(boolean useSSL); + + /** + * Sets the trust store path for SSL connections. + * + * @param keyStore the trust store path. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue null + */ + public TableSessionBuilder trustStore(String keyStore); + + /** + * Sets the trust store password for SSL connections. + * + * @param keyStorePwd the trust store password. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue null + */ + public TableSessionBuilder trustStorePwd(String keyStorePwd); + + /** + * Enables or disables rpc compression for the connection. + * + * @param enableCompression whether to enable compression. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue false + */ + public TableSessionBuilder enableCompression(boolean enableCompression); + + /** + * Sets the connection timeout in milliseconds. + * + * @param connectionTimeoutInMs the connection timeout in milliseconds. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue 0 (no timeout) + */ + public TableSessionBuilder connectionTimeoutInMs(int connectionTimeoutInMs); +} +``` + +## Session Pool + +### ITableSessionPool Interface + +The `ITableSessionPool` interface manages a pool of `ITableSession` instances, enabling efficient reuse of connections and proper cleanup of resources. + +#### Method Overview + +| **Method Name** | **Description** | **Return Value** | **Exceptions** | +| --------------- | ---------------------------------------------------------- | ---------------- | -------------------------- | +| getSession() | Acquires a session from the pool for database interaction. | `ITableSession` | `IoTDBConnectionException` | +| close() | Closes the session pool and releases resources.。 | None | None | + +#### Sample Code + +```Java +/** + * This interface defines a pool for managing {@link ITableSession} instances. + * It provides methods to acquire a session from the pool and to close the pool. + * + *

The implementation should handle the lifecycle of sessions, ensuring efficient + * reuse and proper cleanup of resources. + */ +public interface ITableSessionPool { + + /** + * Acquires an {@link ITableSession} instance from the pool. + * + * @return an {@link ITableSession} instance for interacting with the IoTDB. + * @throws IoTDBConnectionException if there is an issue obtaining a session from the pool. + */ + ITableSession getSession() throws IoTDBConnectionException; + + /** + * Closes the session pool, releasing any held resources. + * + *

Once the pool is closed, no further sessions can be acquired. + */ + void close(); +} +``` + +### TableSessionPoolBuilder Class + +The `TableSessionPoolBuilder` class is a builder for configuring and creating `ITableSessionPool` instances, supporting options like connection settings and pooling behavior. + +#### Parameter Configuration + +| **Parameter** | **Description** | **Default Value** | +|---------------------------------------------------------------| ------------------------------------------------------------ | --------------------------------------------- | +| nodeUrls(List\ nodeUrls) | Sets the list of IoTDB cluster node URLs. | `Collections.singletonList("localhost:6667")` | +| maxSize(int maxSize) | Sets the maximum size of the session pool, i.e., the maximum number of sessions allowed in the pool. | `5` | +| user(String user) | Sets the username for the connection. | `"root"` | +| password(String password) | Sets the password for the connection. | `"root"` | +| database(String database) | Sets the target database name. | `"root"` | +| queryTimeoutInMs(long queryTimeoutInMs) | Sets the query timeout in milliseconds. | `60000`(1 minute) | +| fetchSize(int fetchSize) | Sets the fetch size for query results. | `5000` | +| zoneId(ZoneId zoneId) | Sets the timezone-related `ZoneId`. | `ZoneId.systemDefault()` | +| waitToGetSessionTimeoutInMs(long waitToGetSessionTimeoutInMs) | Sets the timeout duration (in milliseconds) for acquiring a session from the pool. | `30000`(30 seconds) | +| thriftDefaultBufferSize(int thriftDefaultBufferSize) | Sets the default buffer size for the Thrift client (in bytes). | `1024`(1KB) | +| thriftMaxFrameSize(int thriftMaxFrameSize) | Sets the maximum frame size for the Thrift client (in bytes). | `64 * 1024 * 1024`(64MB) | +| enableCompression(boolean enableCompression) | Enables or disables compression for the connection. | `false` | +| enableRedirection(boolean enableRedirection) | Enables or disables redirection for cluster nodes. | `true` | +| connectionTimeoutInMs(int connectionTimeoutInMs) | Sets the connection timeout in milliseconds. | `10000` (10 seconds) | +| enableAutoFetch(boolean enableAutoFetch) | Enables or disables automatic fetching of available DataNodes. | `true` | +| maxRetryCount(int maxRetryCount) | Sets the maximum number of connection retry attempts. | `60` | +| retryIntervalInMs(long retryIntervalInMs) | Sets the interval between retry attempts (in milliseconds). | `500` (500 milliseconds) | +| useSSL(boolean useSSL) | Enables or disables SSL for secure connections. | `false` | +| trustStore(String keyStore) | Sets the path to the trust store for SSL connections. | `null` | +| trustStorePwd(String keyStorePwd) | Sets the password for the SSL trust store. | `null` | + +#### Sample Code + +```Java +/** + * A builder class for constructing instances of {@link ITableSessionPool}. + * + *

This builder provides a fluent API for configuring a session pool, including + * connection settings, session parameters, and pool behavior. + * + *

All configurations have reasonable default values, which can be overridden as needed. + */ +public class TableSessionPoolBuilder { + + /** + * Builds and returns a configured {@link ITableSessionPool} instance. + * + * @return a fully configured {@link ITableSessionPool}. + */ + public ITableSessionPool build(); + + /** + * Sets the list of node URLs for the IoTDB cluster. + * + * @param nodeUrls a list of node URLs. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue Collection.singletonList("localhost:6667") + */ + public TableSessionPoolBuilder nodeUrls(List nodeUrls); + + /** + * Sets the maximum size of the session pool. + * + * @param maxSize the maximum number of sessions allowed in the pool. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue 5 + */ + public TableSessionPoolBuilder maxSize(int maxSize); + + /** + * Sets the username for the connection. + * + * @param user the username. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue "root" + */ + public TableSessionPoolBuilder user(String user); + + /** + * Sets the password for the connection. + * + * @param password the password. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue "root" + */ + public TableSessionPoolBuilder password(String password); + + /** + * Sets the target database name. + * + * @param database the database name. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue "root" + */ + public TableSessionPoolBuilder database(String database); + + /** + * Sets the query timeout in milliseconds. + * + * @param queryTimeoutInMs the query timeout in milliseconds. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue 60000 (1 minute) + */ + public TableSessionPoolBuilder queryTimeoutInMs(long queryTimeoutInMs); + + /** + * Sets the fetch size for query results. + * + * @param fetchSize the fetch size. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue 5000 + */ + public TableSessionPoolBuilder fetchSize(int fetchSize); + + /** + * Sets the {@link ZoneId} for timezone-related operations. + * + * @param zoneId the {@link ZoneId}. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue ZoneId.systemDefault() + */ + public TableSessionPoolBuilder zoneId(ZoneId zoneId); + + /** + * Sets the timeout for waiting to acquire a session from the pool. + * + * @param waitToGetSessionTimeoutInMs the timeout duration in milliseconds. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue 30000 (30 seconds) + */ + public TableSessionPoolBuilder waitToGetSessionTimeoutInMs(long waitToGetSessionTimeoutInMs); + + /** + * Sets the default buffer size for the Thrift client. + * + * @param thriftDefaultBufferSize the buffer size in bytes. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue 1024 (1 KB) + */ + public TableSessionPoolBuilder thriftDefaultBufferSize(int thriftDefaultBufferSize); + + /** + * Sets the maximum frame size for the Thrift client. + * + * @param thriftMaxFrameSize the maximum frame size in bytes. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue 64 * 1024 * 1024 (64 MB) + */ + public TableSessionPoolBuilder thriftMaxFrameSize(int thriftMaxFrameSize); + + /** + * Enables or disables compression for the connection. + * + * @param enableCompression whether to enable compression. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue false + */ + public TableSessionPoolBuilder enableCompression(boolean enableCompression); + + /** + * Enables or disables redirection for cluster nodes. + * + * @param enableRedirection whether to enable redirection. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue true + */ + public TableSessionPoolBuilder enableRedirection(boolean enableRedirection); + + /** + * Sets the connection timeout in milliseconds. + * + * @param connectionTimeoutInMs the connection timeout in milliseconds. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue 10000 (10 seconds) + */ + public TableSessionPoolBuilder connectionTimeoutInMs(int connectionTimeoutInMs); + + /** + * Enables or disables automatic fetching of available DataNodes. + * + * @param enableAutoFetch whether to enable automatic fetching. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue true + */ + public TableSessionPoolBuilder enableAutoFetch(boolean enableAutoFetch); + + /** + * Sets the maximum number of retries for connection attempts. + * + * @param maxRetryCount the maximum retry count. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue 60 + */ + public TableSessionPoolBuilder maxRetryCount(int maxRetryCount); + + /** + * Sets the interval between retries in milliseconds. + * + * @param retryIntervalInMs the interval in milliseconds. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue 500 milliseconds + */ + public TableSessionPoolBuilder retryIntervalInMs(long retryIntervalInMs); + + /** + * Enables or disables SSL for secure connections. + * + * @param useSSL whether to enable SSL. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue false + */ + public TableSessionPoolBuilder useSSL(boolean useSSL); + + /** + * Sets the trust store path for SSL connections. + * + * @param keyStore the trust store path. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue null + */ + public TableSessionPoolBuilder trustStore(String keyStore); + + /** + * Sets the trust store password for SSL connections. + * + * @param keyStorePwd the trust store password. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue null + */ + public TableSessionPoolBuilder trustStorePwd(String keyStorePwd); +} +``` \ No newline at end of file diff --git a/src/UserGuide/latest-Table/API/Programming-Java-Native-API.md b/src/UserGuide/latest-Table/API/Programming-Java-Native-API_timecho.md similarity index 100% rename from src/UserGuide/latest-Table/API/Programming-Java-Native-API.md rename to src/UserGuide/latest-Table/API/Programming-Java-Native-API_timecho.md diff --git a/src/UserGuide/latest-Table/QuickStart/QuickStart_apache.md b/src/UserGuide/latest-Table/QuickStart/QuickStart_apache.md index 2df10e79f..ea7846223 100644 --- a/src/UserGuide/latest-Table/QuickStart/QuickStart_apache.md +++ b/src/UserGuide/latest-Table/QuickStart/QuickStart_apache.md @@ -67,7 +67,7 @@ This guide will assist you in quickly installing and deploying IoTDB. You can qu - Data Synchronization: [Data Sync](../User-Manual/Data-Sync_apache.md) -6. Application Programming Interfaces (APIs): IoTDB provides various application programming interfaces (APIs) to facilitate developers' interaction with IoTDB in applications. Currently supported interfaces include [Java Native API](../API/Programming-Java-Native-API.md)、[Python Native API](../API/Programming-Python-Native-API.md)、[JDBC](../API/Programming-JDBC.md), and more. For more programming interfaces, please refer to the [Application Programming Interfaces] section on the official website. +6. Application Programming Interfaces (APIs): IoTDB provides various application programming interfaces (APIs) to facilitate developers' interaction with IoTDB in applications. Currently supported interfaces include [Java Native API](../API/Programming-Java-Native-API_apache.md)、[Python Native API](../API/Programming-Python-Native-API.md)、[JDBC](../API/Programming-JDBC_apache.md), and more. For more programming interfaces, please refer to the [Application Programming Interfaces] section on the official website. ## Want to learn more technical details? diff --git a/src/UserGuide/latest-Table/QuickStart/QuickStart_timecho.md b/src/UserGuide/latest-Table/QuickStart/QuickStart_timecho.md index 00ba1520e..3bc70e462 100644 --- a/src/UserGuide/latest-Table/QuickStart/QuickStart_timecho.md +++ b/src/UserGuide/latest-Table/QuickStart/QuickStart_timecho.md @@ -74,7 +74,7 @@ This guide will assist you in quickly installing and deploying IoTDB. You can qu - Data Synchronization: [Data Sync](../User-Manual/Data-Sync_timecho.md) -6. Application Programming Interfaces (APIs): IoTDB provides various application programming interfaces (APIs) to facilitate developers' interaction with IoTDB in applications. Currently supported interfaces include [Java Native API](../API/Programming-Java-Native-API.md)、[Python Native API](../API/Programming-Python-Native-API.md)、[JDBC](../API/Programming-JDBC.md), and more. For more programming interfaces, please refer to the [Application Programming Interfaces] section on the official website. +6. Application Programming Interfaces (APIs): IoTDB provides various application programming interfaces (APIs) to facilitate developers' interaction with IoTDB in applications. Currently supported interfaces include [Java Native API](../API/Programming-Java-Native-API_timecho.md)、[Python Native API](../API/Programming-Python-Native-API.md)、[JDBC](../API/Programming-JDBC_timecho.md), and more. For more programming interfaces, please refer to the [Application Programming Interfaces] section on the official website. ## What other convenient tools are available? diff --git a/src/zh/UserGuide/Master/Table/API/Programming-JDBC_apache.md b/src/zh/UserGuide/Master/Table/API/Programming-JDBC_apache.md new file mode 100644 index 000000000..c5a1db5e0 --- /dev/null +++ b/src/zh/UserGuide/Master/Table/API/Programming-JDBC_apache.md @@ -0,0 +1,191 @@ + + +# JDBC接口 + +## 1 功能介绍 + +IoTDB JDBC接口提供了一种标准的方式来与IoTDB数据库进行交互,允许用户通过Java程序执行SQL语句来管理数据库和时间序列数据。它支持数据库的连接、创建、查询、更新和删除操作,以及时间序列数据的批量插入和查询。 + +**注意**: 目前的JDBC实现仅是为与第三方工具连接使用的。使用JDBC(执行插入语句时)无法提供高性能写入。 + +对于Java应用,我们推荐使用Java 原生接口。 + +## 2 使用方式 + +**环境要求:** + +- JDK >= 1.8 +- Maven >= 3.6 + +**在maven中添加依赖:** + +```XML + + + org.apache.iotdb + iotdb-jdbc + 2.0.1-beta + + +``` + +## 3 读写操作 + +### 3.1 功能说明 + +- **写操作**:通过execute方法执行插入、创建数据库、创建时间序列等操作。 +- **读操作**:通过executeQuery方法执行查询操作,并使用ResultSet对象获取查询结果。 + +### 3.2 **方法列表** + +| **方法名** | **描述** | **参数** | **返回值** | +| ------------------------------------------------------------ | ---------------------------------- | ---------------------------------------------------------- | ----------------------------------- | +| Class.forName(String driver) | 加载JDBC驱动类 | driver: JDBC驱动类的名称 | Class: 加载的类对象 | +| DriverManager.getConnection(String url, String username, String password) | 建立数据库连接 | url: 数据库的URLusername: 数据库用户名password: 数据库密码 | Connection: 数据库连接对象 | +| Connection.createStatement() | 创建Statement对象,用于执行SQL语句 | 无 | Statement: SQL语句执行对象 | +| Statement.execute(String sql) | 执行SQL语句,对于非查询语句 | sql: 要执行的SQL语句 | boolean: 指示是否返回ResultSet对象 | +| Statement.executeQuery(String sql) | 执行查询SQL语句并返回结果集 | sql: 要执行的查询SQL语句 | ResultSet: 查询结果集 | +| ResultSet.getMetaData() | 获取结果集的元数据 | 无 | ResultSetMetaData: 结果集元数据对象 | +| ResultSet.next() | 移动到结果集的下一行 | 无 | boolean: 是否成功移动到下一行 | +| ResultSet.getString(int columnIndex) | 获取指定列的字符串值 | columnIndex: 列索引(从1开始) | String: 列的字符串值 | + +## 4 示例代码 + +**注意:使用表模型,必须在 url 中指定 sql_dialect 参数为 table。** + +```Java +String url = "jdbc:iotdb://127.0.0.1:6667?sql_dialect=table"; +``` + +JDBC接口示例代码:[src/main/java/org/apache/iotdb/TableModelJDBCExample.java](https://github.com/apache/iotdb/blob/master/example/jdbc/src/main/java/org/apache/iotdb/TableModelJDBCExample.java) + + +```Java +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb; + +import org.apache.iotdb.jdbc.IoTDBSQLException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; + +public class TableModelJDBCExample { + + private static final Logger LOGGER = LoggerFactory.getLogger(TableModelJDBCExample.class); + + public static void main(String[] args) throws ClassNotFoundException, SQLException { + Class.forName("org.apache.iotdb.jdbc.IoTDBDriver"); + + // don't specify database in url + try (Connection connection = + DriverManager.getConnection( + "jdbc:iotdb://127.0.0.1:6667?sql_dialect=table", "root", "root"); + Statement statement = connection.createStatement()) { + + statement.execute("CREATE DATABASE test1"); + statement.execute("CREATE DATABASE test2"); + + statement.execute("use test2"); + + // or use full qualified table name + statement.execute( + "create table test1.table1(region_id STRING ID, plant_id STRING ID, device_id STRING ID, model STRING ATTRIBUTE, temperature FLOAT MEASUREMENT, humidity DOUBLE MEASUREMENT) with (TTL=3600000)"); + + statement.execute( + "create table table2(region_id STRING ID, plant_id STRING ID, color STRING ATTRIBUTE, temperature FLOAT MEASUREMENT, speed DOUBLE MEASUREMENT) with (TTL=6600000)"); + + // show tables from current database + try (ResultSet resultSet = statement.executeQuery("SHOW TABLES")) { + ResultSetMetaData metaData = resultSet.getMetaData(); + System.out.println(metaData.getColumnCount()); + while (resultSet.next()) { + System.out.println(resultSet.getString(1) + ", " + resultSet.getInt(2)); + } + } + + // show tables by specifying another database + // using SHOW tables FROM + try (ResultSet resultSet = statement.executeQuery("SHOW TABLES FROM test1")) { + ResultSetMetaData metaData = resultSet.getMetaData(); + System.out.println(metaData.getColumnCount()); + while (resultSet.next()) { + System.out.println(resultSet.getString(1) + ", " + resultSet.getInt(2)); + } + } + + } catch (IoTDBSQLException e) { + LOGGER.error("IoTDB Jdbc example error", e); + } + + // specify database in url + try (Connection connection = + DriverManager.getConnection( + "jdbc:iotdb://127.0.0.1:6667/test1?sql_dialect=table", "root", "root"); + Statement statement = connection.createStatement()) { + // show tables from current database test1 + try (ResultSet resultSet = statement.executeQuery("SHOW TABLES")) { + ResultSetMetaData metaData = resultSet.getMetaData(); + System.out.println(metaData.getColumnCount()); + while (resultSet.next()) { + System.out.println(resultSet.getString(1) + ", " + resultSet.getInt(2)); + } + } + + // change database to test2 + statement.execute("use test2"); + + try (ResultSet resultSet = statement.executeQuery("SHOW TABLES")) { + ResultSetMetaData metaData = resultSet.getMetaData(); + System.out.println(metaData.getColumnCount()); + while (resultSet.next()) { + System.out.println(resultSet.getString(1) + ", " + resultSet.getInt(2)); + } + } + } + } +} +``` \ No newline at end of file diff --git a/src/zh/UserGuide/Master/Table/API/Programming-JDBC.md b/src/zh/UserGuide/Master/Table/API/Programming-JDBC_timecho.md similarity index 100% rename from src/zh/UserGuide/Master/Table/API/Programming-JDBC.md rename to src/zh/UserGuide/Master/Table/API/Programming-JDBC_timecho.md diff --git a/src/zh/UserGuide/Master/Table/API/Programming-Java-Native-API_apache.md b/src/zh/UserGuide/Master/Table/API/Programming-Java-Native-API_apache.md new file mode 100644 index 000000000..e390a4be8 --- /dev/null +++ b/src/zh/UserGuide/Master/Table/API/Programming-Java-Native-API_apache.md @@ -0,0 +1,860 @@ + + +# Java Session原生接口 + +## 1 功能介绍 + +IoTDB具备Java原生客户端驱动和对应的连接池,提供对象化接口,可以直接组装时序对象进行写入,无需拼装 SQL。推荐使用连接池,多线程并行操作数据库。 + +## 2 使用方式 + +**环境要求:** + +- JDK >= 1.8 +- Maven >= 3.6 + +**在maven中添加依赖:** + +```XML + + + org.apache.iotdb + iotdb-session + 2.0.1-beta + + +``` + +## 3 读写操作 + +### 3.1 ITableSession接口 + +#### 3.1.1 功能描述 + +ITableSession接口定义了与IoTDB交互的基本操作,可以执行数据插入、查询操作以及关闭会话等,非线程安全。 + +#### 3.1.2 方法列表 + +以下是ITableSession接口中定义的方法及其详细说明: + +| **方法名** | **描述** | **参数** | **返回值** | **返回异常** | +| --------------------------------------------------- | ------------------------------------------------------------ | ----------------------------------------------------------- | -------------- | --------------------------------------------------- | +| insert(Tablet tablet) | 将一个包含时间序列数据的Tablet 对象插入到数据库中 | tablet: 要插入的Tablet对象 | 无 | StatementExecutionExceptionIoTDBConnectionException | +| executeNonQueryStatement(String sql) | 执行非查询SQL语句,如DDL(数据定义语言)或DML(数据操作语言)命令 | sql: 要执行的SQL语句。 | 无 | StatementExecutionExceptionIoTDBConnectionException | +| executeQueryStatement(String sql) | 执行查询SQL语句,并返回包含查询结果的SessionDataSet对象 | sql: 要执行的查询SQL语句。 | SessionDataSet | StatementExecutionExceptionIoTDBConnectionException | +| executeQueryStatement(String sql, long timeoutInMs) | 执行查询SQL语句,并设置查询超时时间(以毫秒为单位) | sql: 要执行的查询SQL语句。timeoutInMs: 查询超时时间(毫秒) | SessionDataSet | StatementExecutionException | +| close() | 关闭会话,释放所持有的资源 | 无 | 无 | IoTDBConnectionException | + +#### 3.1.2 接口展示 + +``` java +/** + * This interface defines a session for interacting with IoTDB tables. + * It supports operations such as data insertion, executing queries, and closing the session. + * Implementations of this interface are expected to manage connections and ensure + * proper resource cleanup. + * + *

Each method may throw exceptions to indicate issues such as connection errors or + * execution failures. + * + *

Since this interface extends {@link AutoCloseable}, it is recommended to use + * try-with-resources to ensure the session is properly closed. + */ +public interface ITableSession extends AutoCloseable { + + /** + * Inserts a {@link Tablet} into the database. + * + * @param tablet the tablet containing time-series data to be inserted. + * @throws StatementExecutionException if an error occurs while executing the statement. + * @throws IoTDBConnectionException if there is an issue with the IoTDB connection. + */ + void insert(Tablet tablet) throws StatementExecutionException, IoTDBConnectionException; + + /** + * Executes a non-query SQL statement, such as a DDL or DML command. + * + * @param sql the SQL statement to execute. + * @throws IoTDBConnectionException if there is an issue with the IoTDB connection. + * @throws StatementExecutionException if an error occurs while executing the statement. + */ + void executeNonQueryStatement(String sql) throws IoTDBConnectionException, StatementExecutionException; + + /** + * Executes a query SQL statement and returns the result set. + * + * @param sql the SQL query statement to execute. + * @return a {@link SessionDataSet} containing the query results. + * @throws StatementExecutionException if an error occurs while executing the statement. + * @throws IoTDBConnectionException if there is an issue with the IoTDB connection. + */ + SessionDataSet executeQueryStatement(String sql) + throws StatementExecutionException, IoTDBConnectionException; + + /** + * Executes a query SQL statement with a specified timeout and returns the result set. + * + * @param sql the SQL query statement to execute. + * @param timeoutInMs the timeout duration in milliseconds for the query execution. + * @return a {@link SessionDataSet} containing the query results. + * @throws StatementExecutionException if an error occurs while executing the statement. + * @throws IoTDBConnectionException if there is an issue with the IoTDB connection. + */ + SessionDataSet executeQueryStatement(String sql, long timeoutInMs) + throws StatementExecutionException, IoTDBConnectionException; + + /** + * Closes the session, releasing any held resources. + * + * @throws IoTDBConnectionException if there is an issue with closing the IoTDB connection. + */ + @Override + void close() throws IoTDBConnectionException; +} +``` + +### 3.2 TableSessionBuilder类 + +#### 3.2.1 功能描述 + +TableSessionBuilder类是一个构建器,用于配置和创建ITableSession接口的实例。它允许开发者设置连接参数、查询参数和安全特性等。 + +#### 3.2.2 配置选项 + +以下是TableSessionBuilder类中可用的配置选项及其默认值: + +| **配置项** | **描述** | **默认值** | +| ---------------------------------------------------- | ---------------------------------------- | ------------------------------------------- | +| nodeUrls(List`` nodeUrls) | 设置IoTDB集群的节点URL列表 | Collections.singletonList("localhost:6667") | +| username(String username) | 设置连接的用户名 | "root" | +| password(String password) | 设置连接的密码 | "root" | +| database(String database) | 设置目标数据库名称 | null | +| queryTimeoutInMs(long queryTimeoutInMs) | 设置查询超时时间(毫秒) | 60000(1分钟) | +| fetchSize(int fetchSize) | 设置查询结果的获取大小 | 5000 | +| zoneId(ZoneId zoneId) | 设置时区相关的ZoneId | ZoneId.systemDefault() | +| thriftDefaultBufferSize(int thriftDefaultBufferSize) | 设置Thrift客户端的默认缓冲区大小(字节) | 1024(1KB) | +| thriftMaxFrameSize(int thriftMaxFrameSize) | 设置Thrift客户端的最大帧大小(字节) | 64 * 1024 * 1024(64MB) | +| enableRedirection(boolean enableRedirection) | 是否启用集群节点的重定向 | true | +| enableAutoFetch(boolean enableAutoFetch) | 是否启用自动获取可用DataNodes | true | +| maxRetryCount(int maxRetryCount) | 设置连接尝试的最大重试次数 | 60 | +| retryIntervalInMs(long retryIntervalInMs) | 设置重试间隔时间(毫秒) | 500 | +| useSSL(boolean useSSL) | 是否启用SSL安全连接 | false | +| trustStore(String keyStore) | 设置SSL连接的信任库路径 | null | +| trustStorePwd(String keyStorePwd) | 设置SSL连接的信任库密码 | null | +| enableCompression(boolean enableCompression) | 是否启用RPC压缩 | false | +| connectionTimeoutInMs(int connectionTimeoutInMs) | 设置连接超时时间(毫秒) | 0(无超时) | + +#### 3.2.3 接口展示 + +``` java +/** + * A builder class for constructing instances of {@link ITableSession}. + * + *

This builder provides a fluent API for configuring various options such as connection + * settings, query parameters, and security features. + * + *

All configurations have reasonable default values, which can be overridden as needed. + */ +public class TableSessionBuilder { + + /** + * Builds and returns a configured {@link ITableSession} instance. + * + * @return a fully configured {@link ITableSession}. + * @throws IoTDBConnectionException if an error occurs while establishing the connection. + */ + public ITableSession build() throws IoTDBConnectionException; + + /** + * Sets the list of node URLs for the IoTDB cluster. + * + * @param nodeUrls a list of node URLs. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue Collection.singletonList("localhost:6667") + */ + public TableSessionBuilder nodeUrls(List nodeUrls); + + /** + * Sets the username for the connection. + * + * @param username the username. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue "root" + */ + public TableSessionBuilder username(String username); + + /** + * Sets the password for the connection. + * + * @param password the password. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue "root" + */ + public TableSessionBuilder password(String password); + + /** + * Sets the target database name. + * + * @param database the database name. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue null + */ + public TableSessionBuilder database(String database); + + /** + * Sets the query timeout in milliseconds. + * + * @param queryTimeoutInMs the query timeout in milliseconds. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue 60000 (1 minute) + */ + public TableSessionBuilder queryTimeoutInMs(long queryTimeoutInMs); + + /** + * Sets the fetch size for query results. + * + * @param fetchSize the fetch size. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue 5000 + */ + public TableSessionBuilder fetchSize(int fetchSize); + + /** + * Sets the {@link ZoneId} for timezone-related operations. + * + * @param zoneId the {@link ZoneId}. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue ZoneId.systemDefault() + */ + public TableSessionBuilder zoneId(ZoneId zoneId); + + /** + * Sets the default init buffer size for the Thrift client. + * + * @param thriftDefaultBufferSize the buffer size in bytes. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue 1024 (1 KB) + */ + public TableSessionBuilder thriftDefaultBufferSize(int thriftDefaultBufferSize); + + /** + * Sets the maximum frame size for the Thrift client. + * + * @param thriftMaxFrameSize the maximum frame size in bytes. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue 64 * 1024 * 1024 (64 MB) + */ + public TableSessionBuilder thriftMaxFrameSize(int thriftMaxFrameSize); + + /** + * Enables or disables redirection for cluster nodes. + * + * @param enableRedirection whether to enable redirection. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue true + */ + public TableSessionBuilder enableRedirection(boolean enableRedirection); + + /** + * Enables or disables automatic fetching of available DataNodes. + * + * @param enableAutoFetch whether to enable automatic fetching. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue true + */ + public TableSessionBuilder enableAutoFetch(boolean enableAutoFetch); + + /** + * Sets the maximum number of retries for connection attempts. + * + * @param maxRetryCount the maximum retry count. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue 60 + */ + public TableSessionBuilder maxRetryCount(int maxRetryCount); + + /** + * Sets the interval between retries in milliseconds. + * + * @param retryIntervalInMs the interval in milliseconds. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue 500 milliseconds + */ + public TableSessionBuilder retryIntervalInMs(long retryIntervalInMs); + + /** + * Enables or disables SSL for secure connections. + * + * @param useSSL whether to enable SSL. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue false + */ + public TableSessionBuilder useSSL(boolean useSSL); + + /** + * Sets the trust store path for SSL connections. + * + * @param keyStore the trust store path. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue null + */ + public TableSessionBuilder trustStore(String keyStore); + + /** + * Sets the trust store password for SSL connections. + * + * @param keyStorePwd the trust store password. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue null + */ + public TableSessionBuilder trustStorePwd(String keyStorePwd); + + /** + * Enables or disables rpc compression for the connection. + * + * @param enableCompression whether to enable compression. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue false + */ + public TableSessionBuilder enableCompression(boolean enableCompression); + + /** + * Sets the connection timeout in milliseconds. + * + * @param connectionTimeoutInMs the connection timeout in milliseconds. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue 0 (no timeout) + */ + public TableSessionBuilder connectionTimeoutInMs(int connectionTimeoutInMs); +} +``` + +## 4 客户端连接池 + +### 4.1 ITableSessionPool 接口 + +#### 4.1.1 功能描述 + +ITableSessionPool 是一个用于管理 ITableSession实例的池。这个池可以帮助我们高效地重用连接,并且在不需要时正确地清理资源, 该接口定义了如何从池中获取会话以及如何关闭池的基本操作。 + +#### 4.1.2 方法列表 + +| **方法名** | **描述** | **返回值** | **返回异常** | +| ------------ | ------------------------------------------------------------ | ------------------ | ------------------------ | +| getSession() | 从池中获取一个 ITableSession 实例,用于与 IoTDB 交互。 | ITableSession 实例 | IoTDBConnectionException | +| close() | 关闭会话池,释放任何持有的资源。关闭后,不能再从池中获取新的会话。 | 无 | 无 | + +#### 4.1.3 接口展示 + +```Java +/** + * This interface defines a pool for managing {@link ITableSession} instances. + * It provides methods to acquire a session from the pool and to close the pool. + * + *

The implementation should handle the lifecycle of sessions, ensuring efficient + * reuse and proper cleanup of resources. + */ +public interface ITableSessionPool { + + /** + * Acquires an {@link ITableSession} instance from the pool. + * + * @return an {@link ITableSession} instance for interacting with the IoTDB. + * @throws IoTDBConnectionException if there is an issue obtaining a session from the pool. + */ + ITableSession getSession() throws IoTDBConnectionException; + + /** + * Closes the session pool, releasing any held resources. + * + *

Once the pool is closed, no further sessions can be acquired. + */ + void close(); +} +``` + +### 4.2 TableSessionPoolBuilder 类 + +#### 4.2.1 功能描述 + +TableSessionPool 的构造器,用于配置和创建 ITableSessionPool 的实例。允许开发者配置连接参数、会话参数和池化行为等。 + +#### 4.2.2 配置选项 + +以下是 TableSessionPoolBuilder 类的可用配置选项及其默认值: + +| **配置项** | **描述** | **默认值** | +| ------------------------------------------------------------ | -------------------------------------------- | ------------------------------------------- | +| nodeUrls(List`` nodeUrls) | 设置IoTDB集群的节点URL列表 | Collections.singletonList("localhost:6667") | +| maxSize(int maxSize) | 设置会话池的最大大小,即池中允许的最大会话数 | 5 | +| user(String user) | 设置连接的用户名 | "root" | +| password(String password) | 设置连接的密码 | "root" | +| database(String database) | 设置目标数据库名称 | "root" | +| queryTimeoutInMs(long queryTimeoutInMs) | 设置查询超时时间(毫秒) | 60000(1分钟) | +| fetchSize(int fetchSize) | 设置查询结果的获取大小 | 5000 | +| zoneId(ZoneId zoneId) | 设置时区相关的 ZoneId | ZoneId.systemDefault() | +| waitToGetSessionTimeoutInMs(long waitToGetSessionTimeoutInMs) | 设置从池中获取会话的超时时间(毫秒) | 30000(30秒) | +| thriftDefaultBufferSize(int thriftDefaultBufferSize) | 设置Thrift客户端的默认缓冲区大小(字节) | 1024(1KB) | +| thriftMaxFrameSize(int thriftMaxFrameSize) | 设置Thrift客户端的最大帧大小(字节) | 64 * 1024 * 1024(64MB) | +| enableCompression(boolean enableCompression) | 是否启用连接的压缩 | false | +| enableRedirection(boolean enableRedirection) | 是否启用集群节点的重定向 | true | +| connectionTimeoutInMs(int connectionTimeoutInMs) | 设置连接超时时间(毫秒) | 10000(10秒) | +| enableAutoFetch(boolean enableAutoFetch) | 是否启用自动获取可用DataNodes | true | +| maxRetryCount(int maxRetryCount) | 设置连接尝试的最大重试次数 | 60 | +| retryIntervalInMs(long retryIntervalInMs) | 设置重试间隔时间(毫秒) | 500 | +| useSSL(boolean useSSL) | 是否启用SSL安全连接 | false | +| trustStore(String keyStore) | 设置SSL连接的信任库路径 | null | +| trustStorePwd(String keyStorePwd) | 设置SSL连接的信任库密码 | null | + +#### 4.1.3 接口展示 + +```Java +/** + * A builder class for constructing instances of {@link ITableSessionPool}. + * + *

This builder provides a fluent API for configuring a session pool, including + * connection settings, session parameters, and pool behavior. + * + *

All configurations have reasonable default values, which can be overridden as needed. + */ +public class TableSessionPoolBuilder { + + /** + * Builds and returns a configured {@link ITableSessionPool} instance. + * + * @return a fully configured {@link ITableSessionPool}. + */ + public ITableSessionPool build(); + + /** + * Sets the list of node URLs for the IoTDB cluster. + * + * @param nodeUrls a list of node URLs. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue Collection.singletonList("localhost:6667") + */ + public TableSessionPoolBuilder nodeUrls(List nodeUrls); + + /** + * Sets the maximum size of the session pool. + * + * @param maxSize the maximum number of sessions allowed in the pool. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue 5 + */ + public TableSessionPoolBuilder maxSize(int maxSize); + + /** + * Sets the username for the connection. + * + * @param user the username. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue "root" + */ + public TableSessionPoolBuilder user(String user); + + /** + * Sets the password for the connection. + * + * @param password the password. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue "root" + */ + public TableSessionPoolBuilder password(String password); + + /** + * Sets the target database name. + * + * @param database the database name. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue "root" + */ + public TableSessionPoolBuilder database(String database); + + /** + * Sets the query timeout in milliseconds. + * + * @param queryTimeoutInMs the query timeout in milliseconds. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue 60000 (1 minute) + */ + public TableSessionPoolBuilder queryTimeoutInMs(long queryTimeoutInMs); + + /** + * Sets the fetch size for query results. + * + * @param fetchSize the fetch size. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue 5000 + */ + public TableSessionPoolBuilder fetchSize(int fetchSize); + + /** + * Sets the {@link ZoneId} for timezone-related operations. + * + * @param zoneId the {@link ZoneId}. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue ZoneId.systemDefault() + */ + public TableSessionPoolBuilder zoneId(ZoneId zoneId); + + /** + * Sets the timeout for waiting to acquire a session from the pool. + * + * @param waitToGetSessionTimeoutInMs the timeout duration in milliseconds. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue 30000 (30 seconds) + */ + public TableSessionPoolBuilder waitToGetSessionTimeoutInMs(long waitToGetSessionTimeoutInMs); + + /** + * Sets the default buffer size for the Thrift client. + * + * @param thriftDefaultBufferSize the buffer size in bytes. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue 1024 (1 KB) + */ + public TableSessionPoolBuilder thriftDefaultBufferSize(int thriftDefaultBufferSize); + + /** + * Sets the maximum frame size for the Thrift client. + * + * @param thriftMaxFrameSize the maximum frame size in bytes. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue 64 * 1024 * 1024 (64 MB) + */ + public TableSessionPoolBuilder thriftMaxFrameSize(int thriftMaxFrameSize); + + /** + * Enables or disables compression for the connection. + * + * @param enableCompression whether to enable compression. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue false + */ + public TableSessionPoolBuilder enableCompression(boolean enableCompression); + + /** + * Enables or disables redirection for cluster nodes. + * + * @param enableRedirection whether to enable redirection. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue true + */ + public TableSessionPoolBuilder enableRedirection(boolean enableRedirection); + + /** + * Sets the connection timeout in milliseconds. + * + * @param connectionTimeoutInMs the connection timeout in milliseconds. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue 10000 (10 seconds) + */ + public TableSessionPoolBuilder connectionTimeoutInMs(int connectionTimeoutInMs); + + /** + * Enables or disables automatic fetching of available DataNodes. + * + * @param enableAutoFetch whether to enable automatic fetching. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue true + */ + public TableSessionPoolBuilder enableAutoFetch(boolean enableAutoFetch); + + /** + * Sets the maximum number of retries for connection attempts. + * + * @param maxRetryCount the maximum retry count. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue 60 + */ + public TableSessionPoolBuilder maxRetryCount(int maxRetryCount); + + /** + * Sets the interval between retries in milliseconds. + * + * @param retryIntervalInMs the interval in milliseconds. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue 500 milliseconds + */ + public TableSessionPoolBuilder retryIntervalInMs(long retryIntervalInMs); + + /** + * Enables or disables SSL for secure connections. + * + * @param useSSL whether to enable SSL. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue false + */ + public TableSessionPoolBuilder useSSL(boolean useSSL); + + /** + * Sets the trust store path for SSL connections. + * + * @param keyStore the trust store path. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue null + */ + public TableSessionPoolBuilder trustStore(String keyStore); + + /** + * Sets the trust store password for SSL connections. + * + * @param keyStorePwd the trust store password. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue null + */ + public TableSessionPoolBuilder trustStorePwd(String keyStorePwd); +} +``` + +## 5 示例代码 + +Session 示例代码:[src/main/java/org/apache/iotdb/TableModelSessionExample.java](https://github.com/apache/iotdb/blob/master/example/session/src/main/java/org/apache/iotdb/TableModelSessionExample.java) + +SessionPool 示例代码:[src/main/java/org/apache/iotdb/TableModelSessionPoolExample.java](https://github.com/apache/iotdb/blob/master/example/session/src/main/java/org/apache/iotdb/TableModelSessionPoolExample.java) + +```Java +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb; + +import org.apache.iotdb.isession.ITableSession; +import org.apache.iotdb.isession.SessionDataSet; +import org.apache.iotdb.isession.pool.ITableSessionPool; +import org.apache.iotdb.rpc.IoTDBConnectionException; +import org.apache.iotdb.rpc.StatementExecutionException; +import org.apache.iotdb.session.pool.TableSessionPoolBuilder; + +import org.apache.tsfile.enums.TSDataType; +import org.apache.tsfile.write.record.Tablet; +import org.apache.tsfile.write.record.Tablet.ColumnCategory; +import org.apache.tsfile.write.schema.IMeasurementSchema; +import org.apache.tsfile.write.schema.MeasurementSchema; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +public class TableModelSessionPoolExample { + + private static final String LOCAL_URL = "127.0.0.1:6667"; + + public static void main(String[] args) { + + // don't specify database in constructor + ITableSessionPool tableSessionPool = + new TableSessionPoolBuilder() + .nodeUrls(Collections.singletonList(LOCAL_URL)) + .user("root") + .password("root") + .maxSize(1) + .build(); + + try (ITableSession session = tableSessionPool.getSession()) { + + session.executeNonQueryStatement("CREATE DATABASE test1"); + session.executeNonQueryStatement("CREATE DATABASE test2"); + + session.executeNonQueryStatement("use test2"); + + // or use full qualified table name + session.executeNonQueryStatement( + "create table test1.table1(" + + "region_id STRING ID, " + + "plant_id STRING ID, " + + "device_id STRING ID, " + + "model STRING ATTRIBUTE, " + + "temperature FLOAT MEASUREMENT, " + + "humidity DOUBLE MEASUREMENT) with (TTL=3600000)"); + + session.executeNonQueryStatement( + "create table table2(" + + "region_id STRING ID, " + + "plant_id STRING ID, " + + "color STRING ATTRIBUTE, " + + "temperature FLOAT MEASUREMENT, " + + "speed DOUBLE MEASUREMENT) with (TTL=6600000)"); + + // show tables from current database + try (SessionDataSet dataSet = session.executeQueryStatement("SHOW TABLES")) { + System.out.println(dataSet.getColumnNames()); + System.out.println(dataSet.getColumnTypes()); + while (dataSet.hasNext()) { + System.out.println(dataSet.next()); + } + } + + // show tables by specifying another database + // using SHOW tables FROM + try (SessionDataSet dataSet = session.executeQueryStatement("SHOW TABLES FROM test1")) { + System.out.println(dataSet.getColumnNames()); + System.out.println(dataSet.getColumnTypes()); + while (dataSet.hasNext()) { + System.out.println(dataSet.next()); + } + } + + // insert table data by tablet + List measurementSchemaList = + new ArrayList<>( + Arrays.asList( + new MeasurementSchema("region_id", TSDataType.STRING), + new MeasurementSchema("plant_id", TSDataType.STRING), + new MeasurementSchema("device_id", TSDataType.STRING), + new MeasurementSchema("model", TSDataType.STRING), + new MeasurementSchema("temperature", TSDataType.FLOAT), + new MeasurementSchema("humidity", TSDataType.DOUBLE))); + List columnTypeList = + new ArrayList<>( + Arrays.asList( + ColumnCategory.ID, + ColumnCategory.ID, + ColumnCategory.ID, + ColumnCategory.ATTRIBUTE, + ColumnCategory.MEASUREMENT, + ColumnCategory.MEASUREMENT)); + Tablet tablet = + new Tablet( + "test1", + IMeasurementSchema.getMeasurementNameList(measurementSchemaList), + IMeasurementSchema.getDataTypeList(measurementSchemaList), + columnTypeList, + 100); + for (long timestamp = 0; timestamp < 100; timestamp++) { + int rowIndex = tablet.getRowSize(); + tablet.addTimestamp(rowIndex, timestamp); + tablet.addValue("region_id", rowIndex, "1"); + tablet.addValue("plant_id", rowIndex, "5"); + tablet.addValue("device_id", rowIndex, "3"); + tablet.addValue("model", rowIndex, "A"); + tablet.addValue("temperature", rowIndex, 37.6F); + tablet.addValue("humidity", rowIndex, 111.1); + if (tablet.getRowSize() == tablet.getMaxRowNumber()) { + session.insert(tablet); + tablet.reset(); + } + } + if (tablet.getRowSize() != 0) { + session.insert(tablet); + tablet.reset(); + } + + // query table data + try (SessionDataSet dataSet = + session.executeQueryStatement( + "select * from test1 " + + "where region_id = '1' and plant_id in ('3', '5') and device_id = '3'")) { + System.out.println(dataSet.getColumnNames()); + System.out.println(dataSet.getColumnTypes()); + while (dataSet.hasNext()) { + System.out.println(dataSet.next()); + } + } + + } catch (IoTDBConnectionException e) { + e.printStackTrace(); + } catch (StatementExecutionException e) { + e.printStackTrace(); + } finally { + tableSessionPool.close(); + } + + // specify database in constructor + tableSessionPool = + new TableSessionPoolBuilder() + .nodeUrls(Collections.singletonList(LOCAL_URL)) + .user("root") + .password("root") + .maxSize(1) + .database("test1") + .build(); + + try (ITableSession session = tableSessionPool.getSession()) { + + // show tables from current database + try (SessionDataSet dataSet = session.executeQueryStatement("SHOW TABLES")) { + System.out.println(dataSet.getColumnNames()); + System.out.println(dataSet.getColumnTypes()); + while (dataSet.hasNext()) { + System.out.println(dataSet.next()); + } + } + + // change database to test2 + session.executeNonQueryStatement("use test2"); + + // show tables by specifying another database + // using SHOW tables FROM + try (SessionDataSet dataSet = session.executeQueryStatement("SHOW TABLES")) { + System.out.println(dataSet.getColumnNames()); + System.out.println(dataSet.getColumnTypes()); + while (dataSet.hasNext()) { + System.out.println(dataSet.next()); + } + } + + } catch (IoTDBConnectionException e) { + e.printStackTrace(); + } catch (StatementExecutionException e) { + e.printStackTrace(); + } + + try (ITableSession session = tableSessionPool.getSession()) { + + // show tables from default database test1 + try (SessionDataSet dataSet = session.executeQueryStatement("SHOW TABLES")) { + System.out.println(dataSet.getColumnNames()); + System.out.println(dataSet.getColumnTypes()); + while (dataSet.hasNext()) { + System.out.println(dataSet.next()); + } + } + + } catch (IoTDBConnectionException e) { + e.printStackTrace(); + } catch (StatementExecutionException e) { + e.printStackTrace(); + } finally { + tableSessionPool.close(); + } + } +} +``` \ No newline at end of file diff --git a/src/zh/UserGuide/Master/Table/API/Programming-Java-Native-API.md b/src/zh/UserGuide/Master/Table/API/Programming-Java-Native-API_timecho.md similarity index 100% rename from src/zh/UserGuide/Master/Table/API/Programming-Java-Native-API.md rename to src/zh/UserGuide/Master/Table/API/Programming-Java-Native-API_timecho.md diff --git a/src/zh/UserGuide/Master/Table/QuickStart/QuickStart_apache.md b/src/zh/UserGuide/Master/Table/QuickStart/QuickStart_apache.md index 03b788d7e..97af35020 100644 --- a/src/zh/UserGuide/Master/Table/QuickStart/QuickStart_apache.md +++ b/src/zh/UserGuide/Master/Table/QuickStart/QuickStart_apache.md @@ -67,7 +67,7 @@ - 数据同步:[数据同步](../User-Manual/Data-Sync_apache.md) -6. 应用编程接口: IoTDB 提供了多种应用编程接口(API),以便于开发者在应用程序中与 IoTDB 进行交互,目前支持[ Java 原生接口](../API/Programming-Java-Native-API.md)、[Python 原生接口](../API/Programming-Python-Native-API.md)、[JDBC](../API/Programming-JDBC.md)等,更多编程接口可参见官网【应用编程接口】其他章节 +6. 应用编程接口: IoTDB 提供了多种应用编程接口(API),以便于开发者在应用程序中与 IoTDB 进行交互,目前支持[ Java 原生接口](../API/Programming-Java-Native-API_apache.md)、[Python 原生接口](../API/Programming-Python-Native-API.md)、[JDBC](../API/Programming-JDBC_apache.md)等,更多编程接口可参见官网【应用编程接口】其他章节 ## 想了解更多技术细节? diff --git a/src/zh/UserGuide/Master/Table/QuickStart/QuickStart_timecho.md b/src/zh/UserGuide/Master/Table/QuickStart/QuickStart_timecho.md index 83b6eab7c..a9748c4d0 100644 --- a/src/zh/UserGuide/Master/Table/QuickStart/QuickStart_timecho.md +++ b/src/zh/UserGuide/Master/Table/QuickStart/QuickStart_timecho.md @@ -73,7 +73,7 @@ - 数据同步:[数据同步](../User-Manual/Data-Sync_timecho.md) -6. 应用编程接口: IoTDB 提供了多种应用编程接口(API),以便于开发者在应用程序中与 IoTDB 进行交互,目前支持[ Java 原生接口](../API/Programming-Java-Native-API.md)、[Python 原生接口](../API/Programming-Python-Native-API.md)、[JDBC](../API/Programming-JDBC.md)等,更多编程接口可参见官网【应用编程接口】其他章节 +6. 应用编程接口: IoTDB 提供了多种应用编程接口(API),以便于开发者在应用程序中与 IoTDB 进行交互,目前支持[ Java 原生接口](../API/Programming-Java-Native-API_timecho.md)、[Python 原生接口](../API/Programming-Python-Native-API.md)、[JDBC](../API/Programming-JDBC_timecho.md)等,更多编程接口可参见官网【应用编程接口】其他章节 ## 还有哪些便捷的周边工具? diff --git a/src/zh/UserGuide/latest-Table/API/Programming-JDBC_apache.md b/src/zh/UserGuide/latest-Table/API/Programming-JDBC_apache.md new file mode 100644 index 000000000..c5a1db5e0 --- /dev/null +++ b/src/zh/UserGuide/latest-Table/API/Programming-JDBC_apache.md @@ -0,0 +1,191 @@ + + +# JDBC接口 + +## 1 功能介绍 + +IoTDB JDBC接口提供了一种标准的方式来与IoTDB数据库进行交互,允许用户通过Java程序执行SQL语句来管理数据库和时间序列数据。它支持数据库的连接、创建、查询、更新和删除操作,以及时间序列数据的批量插入和查询。 + +**注意**: 目前的JDBC实现仅是为与第三方工具连接使用的。使用JDBC(执行插入语句时)无法提供高性能写入。 + +对于Java应用,我们推荐使用Java 原生接口。 + +## 2 使用方式 + +**环境要求:** + +- JDK >= 1.8 +- Maven >= 3.6 + +**在maven中添加依赖:** + +```XML + + + org.apache.iotdb + iotdb-jdbc + 2.0.1-beta + + +``` + +## 3 读写操作 + +### 3.1 功能说明 + +- **写操作**:通过execute方法执行插入、创建数据库、创建时间序列等操作。 +- **读操作**:通过executeQuery方法执行查询操作,并使用ResultSet对象获取查询结果。 + +### 3.2 **方法列表** + +| **方法名** | **描述** | **参数** | **返回值** | +| ------------------------------------------------------------ | ---------------------------------- | ---------------------------------------------------------- | ----------------------------------- | +| Class.forName(String driver) | 加载JDBC驱动类 | driver: JDBC驱动类的名称 | Class: 加载的类对象 | +| DriverManager.getConnection(String url, String username, String password) | 建立数据库连接 | url: 数据库的URLusername: 数据库用户名password: 数据库密码 | Connection: 数据库连接对象 | +| Connection.createStatement() | 创建Statement对象,用于执行SQL语句 | 无 | Statement: SQL语句执行对象 | +| Statement.execute(String sql) | 执行SQL语句,对于非查询语句 | sql: 要执行的SQL语句 | boolean: 指示是否返回ResultSet对象 | +| Statement.executeQuery(String sql) | 执行查询SQL语句并返回结果集 | sql: 要执行的查询SQL语句 | ResultSet: 查询结果集 | +| ResultSet.getMetaData() | 获取结果集的元数据 | 无 | ResultSetMetaData: 结果集元数据对象 | +| ResultSet.next() | 移动到结果集的下一行 | 无 | boolean: 是否成功移动到下一行 | +| ResultSet.getString(int columnIndex) | 获取指定列的字符串值 | columnIndex: 列索引(从1开始) | String: 列的字符串值 | + +## 4 示例代码 + +**注意:使用表模型,必须在 url 中指定 sql_dialect 参数为 table。** + +```Java +String url = "jdbc:iotdb://127.0.0.1:6667?sql_dialect=table"; +``` + +JDBC接口示例代码:[src/main/java/org/apache/iotdb/TableModelJDBCExample.java](https://github.com/apache/iotdb/blob/master/example/jdbc/src/main/java/org/apache/iotdb/TableModelJDBCExample.java) + + +```Java +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb; + +import org.apache.iotdb.jdbc.IoTDBSQLException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; + +public class TableModelJDBCExample { + + private static final Logger LOGGER = LoggerFactory.getLogger(TableModelJDBCExample.class); + + public static void main(String[] args) throws ClassNotFoundException, SQLException { + Class.forName("org.apache.iotdb.jdbc.IoTDBDriver"); + + // don't specify database in url + try (Connection connection = + DriverManager.getConnection( + "jdbc:iotdb://127.0.0.1:6667?sql_dialect=table", "root", "root"); + Statement statement = connection.createStatement()) { + + statement.execute("CREATE DATABASE test1"); + statement.execute("CREATE DATABASE test2"); + + statement.execute("use test2"); + + // or use full qualified table name + statement.execute( + "create table test1.table1(region_id STRING ID, plant_id STRING ID, device_id STRING ID, model STRING ATTRIBUTE, temperature FLOAT MEASUREMENT, humidity DOUBLE MEASUREMENT) with (TTL=3600000)"); + + statement.execute( + "create table table2(region_id STRING ID, plant_id STRING ID, color STRING ATTRIBUTE, temperature FLOAT MEASUREMENT, speed DOUBLE MEASUREMENT) with (TTL=6600000)"); + + // show tables from current database + try (ResultSet resultSet = statement.executeQuery("SHOW TABLES")) { + ResultSetMetaData metaData = resultSet.getMetaData(); + System.out.println(metaData.getColumnCount()); + while (resultSet.next()) { + System.out.println(resultSet.getString(1) + ", " + resultSet.getInt(2)); + } + } + + // show tables by specifying another database + // using SHOW tables FROM + try (ResultSet resultSet = statement.executeQuery("SHOW TABLES FROM test1")) { + ResultSetMetaData metaData = resultSet.getMetaData(); + System.out.println(metaData.getColumnCount()); + while (resultSet.next()) { + System.out.println(resultSet.getString(1) + ", " + resultSet.getInt(2)); + } + } + + } catch (IoTDBSQLException e) { + LOGGER.error("IoTDB Jdbc example error", e); + } + + // specify database in url + try (Connection connection = + DriverManager.getConnection( + "jdbc:iotdb://127.0.0.1:6667/test1?sql_dialect=table", "root", "root"); + Statement statement = connection.createStatement()) { + // show tables from current database test1 + try (ResultSet resultSet = statement.executeQuery("SHOW TABLES")) { + ResultSetMetaData metaData = resultSet.getMetaData(); + System.out.println(metaData.getColumnCount()); + while (resultSet.next()) { + System.out.println(resultSet.getString(1) + ", " + resultSet.getInt(2)); + } + } + + // change database to test2 + statement.execute("use test2"); + + try (ResultSet resultSet = statement.executeQuery("SHOW TABLES")) { + ResultSetMetaData metaData = resultSet.getMetaData(); + System.out.println(metaData.getColumnCount()); + while (resultSet.next()) { + System.out.println(resultSet.getString(1) + ", " + resultSet.getInt(2)); + } + } + } + } +} +``` \ No newline at end of file diff --git a/src/zh/UserGuide/latest-Table/API/Programming-JDBC.md b/src/zh/UserGuide/latest-Table/API/Programming-JDBC_timecho.md similarity index 100% rename from src/zh/UserGuide/latest-Table/API/Programming-JDBC.md rename to src/zh/UserGuide/latest-Table/API/Programming-JDBC_timecho.md diff --git a/src/zh/UserGuide/latest-Table/API/Programming-Java-Native-API_apache.md b/src/zh/UserGuide/latest-Table/API/Programming-Java-Native-API_apache.md new file mode 100644 index 000000000..e390a4be8 --- /dev/null +++ b/src/zh/UserGuide/latest-Table/API/Programming-Java-Native-API_apache.md @@ -0,0 +1,860 @@ + + +# Java Session原生接口 + +## 1 功能介绍 + +IoTDB具备Java原生客户端驱动和对应的连接池,提供对象化接口,可以直接组装时序对象进行写入,无需拼装 SQL。推荐使用连接池,多线程并行操作数据库。 + +## 2 使用方式 + +**环境要求:** + +- JDK >= 1.8 +- Maven >= 3.6 + +**在maven中添加依赖:** + +```XML + + + org.apache.iotdb + iotdb-session + 2.0.1-beta + + +``` + +## 3 读写操作 + +### 3.1 ITableSession接口 + +#### 3.1.1 功能描述 + +ITableSession接口定义了与IoTDB交互的基本操作,可以执行数据插入、查询操作以及关闭会话等,非线程安全。 + +#### 3.1.2 方法列表 + +以下是ITableSession接口中定义的方法及其详细说明: + +| **方法名** | **描述** | **参数** | **返回值** | **返回异常** | +| --------------------------------------------------- | ------------------------------------------------------------ | ----------------------------------------------------------- | -------------- | --------------------------------------------------- | +| insert(Tablet tablet) | 将一个包含时间序列数据的Tablet 对象插入到数据库中 | tablet: 要插入的Tablet对象 | 无 | StatementExecutionExceptionIoTDBConnectionException | +| executeNonQueryStatement(String sql) | 执行非查询SQL语句,如DDL(数据定义语言)或DML(数据操作语言)命令 | sql: 要执行的SQL语句。 | 无 | StatementExecutionExceptionIoTDBConnectionException | +| executeQueryStatement(String sql) | 执行查询SQL语句,并返回包含查询结果的SessionDataSet对象 | sql: 要执行的查询SQL语句。 | SessionDataSet | StatementExecutionExceptionIoTDBConnectionException | +| executeQueryStatement(String sql, long timeoutInMs) | 执行查询SQL语句,并设置查询超时时间(以毫秒为单位) | sql: 要执行的查询SQL语句。timeoutInMs: 查询超时时间(毫秒) | SessionDataSet | StatementExecutionException | +| close() | 关闭会话,释放所持有的资源 | 无 | 无 | IoTDBConnectionException | + +#### 3.1.2 接口展示 + +``` java +/** + * This interface defines a session for interacting with IoTDB tables. + * It supports operations such as data insertion, executing queries, and closing the session. + * Implementations of this interface are expected to manage connections and ensure + * proper resource cleanup. + * + *

Each method may throw exceptions to indicate issues such as connection errors or + * execution failures. + * + *

Since this interface extends {@link AutoCloseable}, it is recommended to use + * try-with-resources to ensure the session is properly closed. + */ +public interface ITableSession extends AutoCloseable { + + /** + * Inserts a {@link Tablet} into the database. + * + * @param tablet the tablet containing time-series data to be inserted. + * @throws StatementExecutionException if an error occurs while executing the statement. + * @throws IoTDBConnectionException if there is an issue with the IoTDB connection. + */ + void insert(Tablet tablet) throws StatementExecutionException, IoTDBConnectionException; + + /** + * Executes a non-query SQL statement, such as a DDL or DML command. + * + * @param sql the SQL statement to execute. + * @throws IoTDBConnectionException if there is an issue with the IoTDB connection. + * @throws StatementExecutionException if an error occurs while executing the statement. + */ + void executeNonQueryStatement(String sql) throws IoTDBConnectionException, StatementExecutionException; + + /** + * Executes a query SQL statement and returns the result set. + * + * @param sql the SQL query statement to execute. + * @return a {@link SessionDataSet} containing the query results. + * @throws StatementExecutionException if an error occurs while executing the statement. + * @throws IoTDBConnectionException if there is an issue with the IoTDB connection. + */ + SessionDataSet executeQueryStatement(String sql) + throws StatementExecutionException, IoTDBConnectionException; + + /** + * Executes a query SQL statement with a specified timeout and returns the result set. + * + * @param sql the SQL query statement to execute. + * @param timeoutInMs the timeout duration in milliseconds for the query execution. + * @return a {@link SessionDataSet} containing the query results. + * @throws StatementExecutionException if an error occurs while executing the statement. + * @throws IoTDBConnectionException if there is an issue with the IoTDB connection. + */ + SessionDataSet executeQueryStatement(String sql, long timeoutInMs) + throws StatementExecutionException, IoTDBConnectionException; + + /** + * Closes the session, releasing any held resources. + * + * @throws IoTDBConnectionException if there is an issue with closing the IoTDB connection. + */ + @Override + void close() throws IoTDBConnectionException; +} +``` + +### 3.2 TableSessionBuilder类 + +#### 3.2.1 功能描述 + +TableSessionBuilder类是一个构建器,用于配置和创建ITableSession接口的实例。它允许开发者设置连接参数、查询参数和安全特性等。 + +#### 3.2.2 配置选项 + +以下是TableSessionBuilder类中可用的配置选项及其默认值: + +| **配置项** | **描述** | **默认值** | +| ---------------------------------------------------- | ---------------------------------------- | ------------------------------------------- | +| nodeUrls(List`` nodeUrls) | 设置IoTDB集群的节点URL列表 | Collections.singletonList("localhost:6667") | +| username(String username) | 设置连接的用户名 | "root" | +| password(String password) | 设置连接的密码 | "root" | +| database(String database) | 设置目标数据库名称 | null | +| queryTimeoutInMs(long queryTimeoutInMs) | 设置查询超时时间(毫秒) | 60000(1分钟) | +| fetchSize(int fetchSize) | 设置查询结果的获取大小 | 5000 | +| zoneId(ZoneId zoneId) | 设置时区相关的ZoneId | ZoneId.systemDefault() | +| thriftDefaultBufferSize(int thriftDefaultBufferSize) | 设置Thrift客户端的默认缓冲区大小(字节) | 1024(1KB) | +| thriftMaxFrameSize(int thriftMaxFrameSize) | 设置Thrift客户端的最大帧大小(字节) | 64 * 1024 * 1024(64MB) | +| enableRedirection(boolean enableRedirection) | 是否启用集群节点的重定向 | true | +| enableAutoFetch(boolean enableAutoFetch) | 是否启用自动获取可用DataNodes | true | +| maxRetryCount(int maxRetryCount) | 设置连接尝试的最大重试次数 | 60 | +| retryIntervalInMs(long retryIntervalInMs) | 设置重试间隔时间(毫秒) | 500 | +| useSSL(boolean useSSL) | 是否启用SSL安全连接 | false | +| trustStore(String keyStore) | 设置SSL连接的信任库路径 | null | +| trustStorePwd(String keyStorePwd) | 设置SSL连接的信任库密码 | null | +| enableCompression(boolean enableCompression) | 是否启用RPC压缩 | false | +| connectionTimeoutInMs(int connectionTimeoutInMs) | 设置连接超时时间(毫秒) | 0(无超时) | + +#### 3.2.3 接口展示 + +``` java +/** + * A builder class for constructing instances of {@link ITableSession}. + * + *

This builder provides a fluent API for configuring various options such as connection + * settings, query parameters, and security features. + * + *

All configurations have reasonable default values, which can be overridden as needed. + */ +public class TableSessionBuilder { + + /** + * Builds and returns a configured {@link ITableSession} instance. + * + * @return a fully configured {@link ITableSession}. + * @throws IoTDBConnectionException if an error occurs while establishing the connection. + */ + public ITableSession build() throws IoTDBConnectionException; + + /** + * Sets the list of node URLs for the IoTDB cluster. + * + * @param nodeUrls a list of node URLs. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue Collection.singletonList("localhost:6667") + */ + public TableSessionBuilder nodeUrls(List nodeUrls); + + /** + * Sets the username for the connection. + * + * @param username the username. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue "root" + */ + public TableSessionBuilder username(String username); + + /** + * Sets the password for the connection. + * + * @param password the password. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue "root" + */ + public TableSessionBuilder password(String password); + + /** + * Sets the target database name. + * + * @param database the database name. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue null + */ + public TableSessionBuilder database(String database); + + /** + * Sets the query timeout in milliseconds. + * + * @param queryTimeoutInMs the query timeout in milliseconds. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue 60000 (1 minute) + */ + public TableSessionBuilder queryTimeoutInMs(long queryTimeoutInMs); + + /** + * Sets the fetch size for query results. + * + * @param fetchSize the fetch size. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue 5000 + */ + public TableSessionBuilder fetchSize(int fetchSize); + + /** + * Sets the {@link ZoneId} for timezone-related operations. + * + * @param zoneId the {@link ZoneId}. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue ZoneId.systemDefault() + */ + public TableSessionBuilder zoneId(ZoneId zoneId); + + /** + * Sets the default init buffer size for the Thrift client. + * + * @param thriftDefaultBufferSize the buffer size in bytes. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue 1024 (1 KB) + */ + public TableSessionBuilder thriftDefaultBufferSize(int thriftDefaultBufferSize); + + /** + * Sets the maximum frame size for the Thrift client. + * + * @param thriftMaxFrameSize the maximum frame size in bytes. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue 64 * 1024 * 1024 (64 MB) + */ + public TableSessionBuilder thriftMaxFrameSize(int thriftMaxFrameSize); + + /** + * Enables or disables redirection for cluster nodes. + * + * @param enableRedirection whether to enable redirection. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue true + */ + public TableSessionBuilder enableRedirection(boolean enableRedirection); + + /** + * Enables or disables automatic fetching of available DataNodes. + * + * @param enableAutoFetch whether to enable automatic fetching. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue true + */ + public TableSessionBuilder enableAutoFetch(boolean enableAutoFetch); + + /** + * Sets the maximum number of retries for connection attempts. + * + * @param maxRetryCount the maximum retry count. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue 60 + */ + public TableSessionBuilder maxRetryCount(int maxRetryCount); + + /** + * Sets the interval between retries in milliseconds. + * + * @param retryIntervalInMs the interval in milliseconds. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue 500 milliseconds + */ + public TableSessionBuilder retryIntervalInMs(long retryIntervalInMs); + + /** + * Enables or disables SSL for secure connections. + * + * @param useSSL whether to enable SSL. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue false + */ + public TableSessionBuilder useSSL(boolean useSSL); + + /** + * Sets the trust store path for SSL connections. + * + * @param keyStore the trust store path. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue null + */ + public TableSessionBuilder trustStore(String keyStore); + + /** + * Sets the trust store password for SSL connections. + * + * @param keyStorePwd the trust store password. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue null + */ + public TableSessionBuilder trustStorePwd(String keyStorePwd); + + /** + * Enables or disables rpc compression for the connection. + * + * @param enableCompression whether to enable compression. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue false + */ + public TableSessionBuilder enableCompression(boolean enableCompression); + + /** + * Sets the connection timeout in milliseconds. + * + * @param connectionTimeoutInMs the connection timeout in milliseconds. + * @return the current {@link TableSessionBuilder} instance. + * @defaultValue 0 (no timeout) + */ + public TableSessionBuilder connectionTimeoutInMs(int connectionTimeoutInMs); +} +``` + +## 4 客户端连接池 + +### 4.1 ITableSessionPool 接口 + +#### 4.1.1 功能描述 + +ITableSessionPool 是一个用于管理 ITableSession实例的池。这个池可以帮助我们高效地重用连接,并且在不需要时正确地清理资源, 该接口定义了如何从池中获取会话以及如何关闭池的基本操作。 + +#### 4.1.2 方法列表 + +| **方法名** | **描述** | **返回值** | **返回异常** | +| ------------ | ------------------------------------------------------------ | ------------------ | ------------------------ | +| getSession() | 从池中获取一个 ITableSession 实例,用于与 IoTDB 交互。 | ITableSession 实例 | IoTDBConnectionException | +| close() | 关闭会话池,释放任何持有的资源。关闭后,不能再从池中获取新的会话。 | 无 | 无 | + +#### 4.1.3 接口展示 + +```Java +/** + * This interface defines a pool for managing {@link ITableSession} instances. + * It provides methods to acquire a session from the pool and to close the pool. + * + *

The implementation should handle the lifecycle of sessions, ensuring efficient + * reuse and proper cleanup of resources. + */ +public interface ITableSessionPool { + + /** + * Acquires an {@link ITableSession} instance from the pool. + * + * @return an {@link ITableSession} instance for interacting with the IoTDB. + * @throws IoTDBConnectionException if there is an issue obtaining a session from the pool. + */ + ITableSession getSession() throws IoTDBConnectionException; + + /** + * Closes the session pool, releasing any held resources. + * + *

Once the pool is closed, no further sessions can be acquired. + */ + void close(); +} +``` + +### 4.2 TableSessionPoolBuilder 类 + +#### 4.2.1 功能描述 + +TableSessionPool 的构造器,用于配置和创建 ITableSessionPool 的实例。允许开发者配置连接参数、会话参数和池化行为等。 + +#### 4.2.2 配置选项 + +以下是 TableSessionPoolBuilder 类的可用配置选项及其默认值: + +| **配置项** | **描述** | **默认值** | +| ------------------------------------------------------------ | -------------------------------------------- | ------------------------------------------- | +| nodeUrls(List`` nodeUrls) | 设置IoTDB集群的节点URL列表 | Collections.singletonList("localhost:6667") | +| maxSize(int maxSize) | 设置会话池的最大大小,即池中允许的最大会话数 | 5 | +| user(String user) | 设置连接的用户名 | "root" | +| password(String password) | 设置连接的密码 | "root" | +| database(String database) | 设置目标数据库名称 | "root" | +| queryTimeoutInMs(long queryTimeoutInMs) | 设置查询超时时间(毫秒) | 60000(1分钟) | +| fetchSize(int fetchSize) | 设置查询结果的获取大小 | 5000 | +| zoneId(ZoneId zoneId) | 设置时区相关的 ZoneId | ZoneId.systemDefault() | +| waitToGetSessionTimeoutInMs(long waitToGetSessionTimeoutInMs) | 设置从池中获取会话的超时时间(毫秒) | 30000(30秒) | +| thriftDefaultBufferSize(int thriftDefaultBufferSize) | 设置Thrift客户端的默认缓冲区大小(字节) | 1024(1KB) | +| thriftMaxFrameSize(int thriftMaxFrameSize) | 设置Thrift客户端的最大帧大小(字节) | 64 * 1024 * 1024(64MB) | +| enableCompression(boolean enableCompression) | 是否启用连接的压缩 | false | +| enableRedirection(boolean enableRedirection) | 是否启用集群节点的重定向 | true | +| connectionTimeoutInMs(int connectionTimeoutInMs) | 设置连接超时时间(毫秒) | 10000(10秒) | +| enableAutoFetch(boolean enableAutoFetch) | 是否启用自动获取可用DataNodes | true | +| maxRetryCount(int maxRetryCount) | 设置连接尝试的最大重试次数 | 60 | +| retryIntervalInMs(long retryIntervalInMs) | 设置重试间隔时间(毫秒) | 500 | +| useSSL(boolean useSSL) | 是否启用SSL安全连接 | false | +| trustStore(String keyStore) | 设置SSL连接的信任库路径 | null | +| trustStorePwd(String keyStorePwd) | 设置SSL连接的信任库密码 | null | + +#### 4.1.3 接口展示 + +```Java +/** + * A builder class for constructing instances of {@link ITableSessionPool}. + * + *

This builder provides a fluent API for configuring a session pool, including + * connection settings, session parameters, and pool behavior. + * + *

All configurations have reasonable default values, which can be overridden as needed. + */ +public class TableSessionPoolBuilder { + + /** + * Builds and returns a configured {@link ITableSessionPool} instance. + * + * @return a fully configured {@link ITableSessionPool}. + */ + public ITableSessionPool build(); + + /** + * Sets the list of node URLs for the IoTDB cluster. + * + * @param nodeUrls a list of node URLs. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue Collection.singletonList("localhost:6667") + */ + public TableSessionPoolBuilder nodeUrls(List nodeUrls); + + /** + * Sets the maximum size of the session pool. + * + * @param maxSize the maximum number of sessions allowed in the pool. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue 5 + */ + public TableSessionPoolBuilder maxSize(int maxSize); + + /** + * Sets the username for the connection. + * + * @param user the username. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue "root" + */ + public TableSessionPoolBuilder user(String user); + + /** + * Sets the password for the connection. + * + * @param password the password. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue "root" + */ + public TableSessionPoolBuilder password(String password); + + /** + * Sets the target database name. + * + * @param database the database name. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue "root" + */ + public TableSessionPoolBuilder database(String database); + + /** + * Sets the query timeout in milliseconds. + * + * @param queryTimeoutInMs the query timeout in milliseconds. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue 60000 (1 minute) + */ + public TableSessionPoolBuilder queryTimeoutInMs(long queryTimeoutInMs); + + /** + * Sets the fetch size for query results. + * + * @param fetchSize the fetch size. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue 5000 + */ + public TableSessionPoolBuilder fetchSize(int fetchSize); + + /** + * Sets the {@link ZoneId} for timezone-related operations. + * + * @param zoneId the {@link ZoneId}. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue ZoneId.systemDefault() + */ + public TableSessionPoolBuilder zoneId(ZoneId zoneId); + + /** + * Sets the timeout for waiting to acquire a session from the pool. + * + * @param waitToGetSessionTimeoutInMs the timeout duration in milliseconds. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue 30000 (30 seconds) + */ + public TableSessionPoolBuilder waitToGetSessionTimeoutInMs(long waitToGetSessionTimeoutInMs); + + /** + * Sets the default buffer size for the Thrift client. + * + * @param thriftDefaultBufferSize the buffer size in bytes. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue 1024 (1 KB) + */ + public TableSessionPoolBuilder thriftDefaultBufferSize(int thriftDefaultBufferSize); + + /** + * Sets the maximum frame size for the Thrift client. + * + * @param thriftMaxFrameSize the maximum frame size in bytes. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue 64 * 1024 * 1024 (64 MB) + */ + public TableSessionPoolBuilder thriftMaxFrameSize(int thriftMaxFrameSize); + + /** + * Enables or disables compression for the connection. + * + * @param enableCompression whether to enable compression. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue false + */ + public TableSessionPoolBuilder enableCompression(boolean enableCompression); + + /** + * Enables or disables redirection for cluster nodes. + * + * @param enableRedirection whether to enable redirection. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue true + */ + public TableSessionPoolBuilder enableRedirection(boolean enableRedirection); + + /** + * Sets the connection timeout in milliseconds. + * + * @param connectionTimeoutInMs the connection timeout in milliseconds. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue 10000 (10 seconds) + */ + public TableSessionPoolBuilder connectionTimeoutInMs(int connectionTimeoutInMs); + + /** + * Enables or disables automatic fetching of available DataNodes. + * + * @param enableAutoFetch whether to enable automatic fetching. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue true + */ + public TableSessionPoolBuilder enableAutoFetch(boolean enableAutoFetch); + + /** + * Sets the maximum number of retries for connection attempts. + * + * @param maxRetryCount the maximum retry count. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue 60 + */ + public TableSessionPoolBuilder maxRetryCount(int maxRetryCount); + + /** + * Sets the interval between retries in milliseconds. + * + * @param retryIntervalInMs the interval in milliseconds. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue 500 milliseconds + */ + public TableSessionPoolBuilder retryIntervalInMs(long retryIntervalInMs); + + /** + * Enables or disables SSL for secure connections. + * + * @param useSSL whether to enable SSL. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue false + */ + public TableSessionPoolBuilder useSSL(boolean useSSL); + + /** + * Sets the trust store path for SSL connections. + * + * @param keyStore the trust store path. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue null + */ + public TableSessionPoolBuilder trustStore(String keyStore); + + /** + * Sets the trust store password for SSL connections. + * + * @param keyStorePwd the trust store password. + * @return the current {@link TableSessionPoolBuilder} instance. + * @defaultValue null + */ + public TableSessionPoolBuilder trustStorePwd(String keyStorePwd); +} +``` + +## 5 示例代码 + +Session 示例代码:[src/main/java/org/apache/iotdb/TableModelSessionExample.java](https://github.com/apache/iotdb/blob/master/example/session/src/main/java/org/apache/iotdb/TableModelSessionExample.java) + +SessionPool 示例代码:[src/main/java/org/apache/iotdb/TableModelSessionPoolExample.java](https://github.com/apache/iotdb/blob/master/example/session/src/main/java/org/apache/iotdb/TableModelSessionPoolExample.java) + +```Java +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb; + +import org.apache.iotdb.isession.ITableSession; +import org.apache.iotdb.isession.SessionDataSet; +import org.apache.iotdb.isession.pool.ITableSessionPool; +import org.apache.iotdb.rpc.IoTDBConnectionException; +import org.apache.iotdb.rpc.StatementExecutionException; +import org.apache.iotdb.session.pool.TableSessionPoolBuilder; + +import org.apache.tsfile.enums.TSDataType; +import org.apache.tsfile.write.record.Tablet; +import org.apache.tsfile.write.record.Tablet.ColumnCategory; +import org.apache.tsfile.write.schema.IMeasurementSchema; +import org.apache.tsfile.write.schema.MeasurementSchema; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +public class TableModelSessionPoolExample { + + private static final String LOCAL_URL = "127.0.0.1:6667"; + + public static void main(String[] args) { + + // don't specify database in constructor + ITableSessionPool tableSessionPool = + new TableSessionPoolBuilder() + .nodeUrls(Collections.singletonList(LOCAL_URL)) + .user("root") + .password("root") + .maxSize(1) + .build(); + + try (ITableSession session = tableSessionPool.getSession()) { + + session.executeNonQueryStatement("CREATE DATABASE test1"); + session.executeNonQueryStatement("CREATE DATABASE test2"); + + session.executeNonQueryStatement("use test2"); + + // or use full qualified table name + session.executeNonQueryStatement( + "create table test1.table1(" + + "region_id STRING ID, " + + "plant_id STRING ID, " + + "device_id STRING ID, " + + "model STRING ATTRIBUTE, " + + "temperature FLOAT MEASUREMENT, " + + "humidity DOUBLE MEASUREMENT) with (TTL=3600000)"); + + session.executeNonQueryStatement( + "create table table2(" + + "region_id STRING ID, " + + "plant_id STRING ID, " + + "color STRING ATTRIBUTE, " + + "temperature FLOAT MEASUREMENT, " + + "speed DOUBLE MEASUREMENT) with (TTL=6600000)"); + + // show tables from current database + try (SessionDataSet dataSet = session.executeQueryStatement("SHOW TABLES")) { + System.out.println(dataSet.getColumnNames()); + System.out.println(dataSet.getColumnTypes()); + while (dataSet.hasNext()) { + System.out.println(dataSet.next()); + } + } + + // show tables by specifying another database + // using SHOW tables FROM + try (SessionDataSet dataSet = session.executeQueryStatement("SHOW TABLES FROM test1")) { + System.out.println(dataSet.getColumnNames()); + System.out.println(dataSet.getColumnTypes()); + while (dataSet.hasNext()) { + System.out.println(dataSet.next()); + } + } + + // insert table data by tablet + List measurementSchemaList = + new ArrayList<>( + Arrays.asList( + new MeasurementSchema("region_id", TSDataType.STRING), + new MeasurementSchema("plant_id", TSDataType.STRING), + new MeasurementSchema("device_id", TSDataType.STRING), + new MeasurementSchema("model", TSDataType.STRING), + new MeasurementSchema("temperature", TSDataType.FLOAT), + new MeasurementSchema("humidity", TSDataType.DOUBLE))); + List columnTypeList = + new ArrayList<>( + Arrays.asList( + ColumnCategory.ID, + ColumnCategory.ID, + ColumnCategory.ID, + ColumnCategory.ATTRIBUTE, + ColumnCategory.MEASUREMENT, + ColumnCategory.MEASUREMENT)); + Tablet tablet = + new Tablet( + "test1", + IMeasurementSchema.getMeasurementNameList(measurementSchemaList), + IMeasurementSchema.getDataTypeList(measurementSchemaList), + columnTypeList, + 100); + for (long timestamp = 0; timestamp < 100; timestamp++) { + int rowIndex = tablet.getRowSize(); + tablet.addTimestamp(rowIndex, timestamp); + tablet.addValue("region_id", rowIndex, "1"); + tablet.addValue("plant_id", rowIndex, "5"); + tablet.addValue("device_id", rowIndex, "3"); + tablet.addValue("model", rowIndex, "A"); + tablet.addValue("temperature", rowIndex, 37.6F); + tablet.addValue("humidity", rowIndex, 111.1); + if (tablet.getRowSize() == tablet.getMaxRowNumber()) { + session.insert(tablet); + tablet.reset(); + } + } + if (tablet.getRowSize() != 0) { + session.insert(tablet); + tablet.reset(); + } + + // query table data + try (SessionDataSet dataSet = + session.executeQueryStatement( + "select * from test1 " + + "where region_id = '1' and plant_id in ('3', '5') and device_id = '3'")) { + System.out.println(dataSet.getColumnNames()); + System.out.println(dataSet.getColumnTypes()); + while (dataSet.hasNext()) { + System.out.println(dataSet.next()); + } + } + + } catch (IoTDBConnectionException e) { + e.printStackTrace(); + } catch (StatementExecutionException e) { + e.printStackTrace(); + } finally { + tableSessionPool.close(); + } + + // specify database in constructor + tableSessionPool = + new TableSessionPoolBuilder() + .nodeUrls(Collections.singletonList(LOCAL_URL)) + .user("root") + .password("root") + .maxSize(1) + .database("test1") + .build(); + + try (ITableSession session = tableSessionPool.getSession()) { + + // show tables from current database + try (SessionDataSet dataSet = session.executeQueryStatement("SHOW TABLES")) { + System.out.println(dataSet.getColumnNames()); + System.out.println(dataSet.getColumnTypes()); + while (dataSet.hasNext()) { + System.out.println(dataSet.next()); + } + } + + // change database to test2 + session.executeNonQueryStatement("use test2"); + + // show tables by specifying another database + // using SHOW tables FROM + try (SessionDataSet dataSet = session.executeQueryStatement("SHOW TABLES")) { + System.out.println(dataSet.getColumnNames()); + System.out.println(dataSet.getColumnTypes()); + while (dataSet.hasNext()) { + System.out.println(dataSet.next()); + } + } + + } catch (IoTDBConnectionException e) { + e.printStackTrace(); + } catch (StatementExecutionException e) { + e.printStackTrace(); + } + + try (ITableSession session = tableSessionPool.getSession()) { + + // show tables from default database test1 + try (SessionDataSet dataSet = session.executeQueryStatement("SHOW TABLES")) { + System.out.println(dataSet.getColumnNames()); + System.out.println(dataSet.getColumnTypes()); + while (dataSet.hasNext()) { + System.out.println(dataSet.next()); + } + } + + } catch (IoTDBConnectionException e) { + e.printStackTrace(); + } catch (StatementExecutionException e) { + e.printStackTrace(); + } finally { + tableSessionPool.close(); + } + } +} +``` \ No newline at end of file diff --git a/src/zh/UserGuide/latest-Table/API/Programming-Java-Native-API.md b/src/zh/UserGuide/latest-Table/API/Programming-Java-Native-API_timecho.md similarity index 100% rename from src/zh/UserGuide/latest-Table/API/Programming-Java-Native-API.md rename to src/zh/UserGuide/latest-Table/API/Programming-Java-Native-API_timecho.md diff --git a/src/zh/UserGuide/latest-Table/QuickStart/QuickStart_apache.md b/src/zh/UserGuide/latest-Table/QuickStart/QuickStart_apache.md index 9f37a9b56..197b0efc4 100644 --- a/src/zh/UserGuide/latest-Table/QuickStart/QuickStart_apache.md +++ b/src/zh/UserGuide/latest-Table/QuickStart/QuickStart_apache.md @@ -66,7 +66,7 @@ - 数据同步:[数据同步](../User-Manual/Data-Sync_apache.md) -6. 应用编程接口: IoTDB 提供了多种应用编程接口(API),以便于开发者在应用程序中与 IoTDB 进行交互,目前支持[ Java 原生接口](../API/Programming-Java-Native-API.md)、[Python 原生接口](../API/Programming-Python-Native-API.md)、[JDBC](../API/Programming-JDBC.md)等,更多编程接口可参见官网【应用编程接口】其他章节 +6. 应用编程接口: IoTDB 提供了多种应用编程接口(API),以便于开发者在应用程序中与 IoTDB 进行交互,目前支持[ Java 原生接口](../API/Programming-Java-Native-API_apache.md)、[Python 原生接口](../API/Programming-Python-Native-API.md)、[JDBC](../API/Programming-JDBC_apache.md)等,更多编程接口可参见官网【应用编程接口】其他章节 ## 想了解更多技术细节? diff --git a/src/zh/UserGuide/latest-Table/QuickStart/QuickStart_timecho.md b/src/zh/UserGuide/latest-Table/QuickStart/QuickStart_timecho.md index 83b6eab7c..a9748c4d0 100644 --- a/src/zh/UserGuide/latest-Table/QuickStart/QuickStart_timecho.md +++ b/src/zh/UserGuide/latest-Table/QuickStart/QuickStart_timecho.md @@ -73,7 +73,7 @@ - 数据同步:[数据同步](../User-Manual/Data-Sync_timecho.md) -6. 应用编程接口: IoTDB 提供了多种应用编程接口(API),以便于开发者在应用程序中与 IoTDB 进行交互,目前支持[ Java 原生接口](../API/Programming-Java-Native-API.md)、[Python 原生接口](../API/Programming-Python-Native-API.md)、[JDBC](../API/Programming-JDBC.md)等,更多编程接口可参见官网【应用编程接口】其他章节 +6. 应用编程接口: IoTDB 提供了多种应用编程接口(API),以便于开发者在应用程序中与 IoTDB 进行交互,目前支持[ Java 原生接口](../API/Programming-Java-Native-API_timecho.md)、[Python 原生接口](../API/Programming-Python-Native-API.md)、[JDBC](../API/Programming-JDBC_timecho.md)等,更多编程接口可参见官网【应用编程接口】其他章节 ## 还有哪些便捷的周边工具?