docs/en/14-reference/05-connector/14-java.md
import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; import RequestId from "../../assets/resources/_request_id.mdx";
taos-jdbcdriver is the official Java connector for TDengine, allowing Java developers to develop applications that access the TDengine database. taos-jdbcdriver implements the interfaces of the JDBC driver standard.
:::info
The JDBC driver implementation for TDengine strives to be consistent with relational database drivers. However, due to differences in use cases and technical features between TDengine and relational object databases, there are some differences between taos-jdbcdriver and traditional JDBC drivers. Please note the following when using it:
:::
| taos-jdbcdriver Version | Major Changes | TDengine Version |
|---|---|---|
| 3.8.1 | Decimal and Blob types support writing via parameter binding. | - |
| 3.8.0 | 1. Load balancing adopts the least connections algorithm. |
getTables method requires an identifier quote string. | - |
| 3.7.7 | 1. Fixed the issue of loading configuration files on the Windows platform.setObject method for parameter binding. | - |
| 3.7.5 | 1. WebSocket connections support load balancing.varcharAsString in connection property.After an error occurs, the error information and error code can be obtained through SQLException:
{{#include docs/examples/JDBC/JDBCDemo/src/main/java/com/taos/example/JdbcBasicDemo.java:jdbc_exception}}
For error code information please refer to Error Codes
TDengine currently supports timestamp, numeric, character, boolean types, and the corresponding Java type conversions are as follows:
| TDengine DataType | JDBCType | Remark |
|---|---|---|
| TIMESTAMP | java.sql.Timestamp | |
| BOOL | java.lang.Boolean | |
| TINYINT | java.lang.Byte | |
| TINYINT UNSIGNED | java.lang.Short | only supported in WebSocket connections |
| SMALLINT | java.lang.Short | |
| SMALLINT UNSIGNED | java.lang.Integer | only supported in WebSocket connections |
| INT | java.lang.Integer | |
| INT UNSIGNED | java.lang.Long | only supported in WebSocket connections |
| BIGINT | java.lang.Long | |
| BIGINT UNSIGNED | java.math.BigInteger | only supported in WebSocket connections |
| FLOAT | java.lang.Float | |
| DOUBLE | java.lang.Double | |
| VARCHAR/BINARY | byte[] | Setting the varcharAsString parameter to true on a WebSocket connection can map it to the String type. |
| NCHAR | java.lang.String | |
| JSON | java.lang.String | only supported in tags |
| VARBINARY | byte[] | |
| GEOMETRY | byte[] | |
| BLOB | byte[] | Only supported for columns in WebSocket connections. |
| DECIMAL | java.math.BigDecimal | Only supported for columns in WebSocket connections. |
Note: Due to historical reasons, the BINARY type in TDengine is not truly binary data and is no longer recommended. Please use VARBINARY type instead.
GEOMETRY type is binary data in little endian byte order, complying with the WKB standard. For more details, please refer to Data Types
For the WKB standard, please refer to Well-Known Binary (WKB)
For the Java connector, you can use the jts library to conveniently create GEOMETRY type objects, serialize them, and write to TDengine. Here is an example Geometry Example
The source code for the example programs is located in TDengine/docs/examples/JDBC:
Please refer to:
addBatch() and executeBatch() for "batch writing/updating"?Reason: In TDengine's JDBC implementation, SQL statements submitted through the addBatch method are executed in the order they were added, which does not reduce the number of interactions with the server and does not lead to performance improvements.
Solutions: 1. Concatenate multiple values in one insert statement; 2. Use multi-threading for concurrent insertion; 3. Use parameter binding for writing
Reason: The program cannot find the required local function library taos.
Solution: On Windows, you can copy C:\TDengine\driver\taos.dll to the C:\Windows\System32\ directory. On Linux, create the following symlink ln -s /usr/local/taos/driver/libtaos.so.x.x.x.x /usr/lib/libtaos.so. On macOS, create a symlink ln -s /usr/local/lib/libtaos.dylib.
Reason: TDengine currently only supports 64-bit JDK.
Solution: Reinstall 64-bit JDK.
Reason: taos-jdbcdriver version 3.* only supports TDengine version 3.0 and above.
Solution: Use taos-jdbcdriver version 2.to connect to TDengine version 2..
Reason: taos-jdbcdriver version 3.0.1 requires JDK 11+ environment.
Solution: Switch to taos-jdbcdriver version 3.0.2+.
Background: Starting from taos-jdbcdriver 3.4.0, WebSocket connection is recommended over REST connection.
Migration Steps:
a. Change driver class from com.taosdata.jdbc.rs.RestfulDriver to com.taosdata.jdbc.ws.WebSocketDriver.
b. Update JDBC URL from jdbc:TAOS-RS:// to jdbc:TAOS-WS://.
c. Remove batchfetch=true parameter, this parameter is not needed.
d. Test and verify functionality works correctly.
Benefits: WebSocket connection provides lower latency, better performance, auto-reconnect support, and richer features.
For other issues, please refer to FAQ
taos-jdbcdriver implements the JDBC standard Driver interface, providing 2 implementation classes.
com.taosdata.jdbc.ws.WebSocketDriver for WebSocket connections.com.taosdata.jdbc.TSDBDriver for native connections.The JDBC URL format for TDengine is:
jdbc:[TAOS|TAOS-WS]://[host1:port1,host2:port2,...,hostN:portN]/[database_name]?[user={user}|&password={password}|&charset={charset}|&cfgdir={config_dir}|&locale={locale}|&timezone={timezone}]
[::1] or [2001:db8:1234:5678::1]) to avoid port number parsing conflicts.Native Connection
jdbc:TAOS://taosdemo.com:6030/power?user=root&password=taosdata, using the TSDBDriver for native JDBC connection, establishes a connection to the host taosdemo.com, port 6030 (TDengine's default port), and database name power. This URL specifies the username (user) as root and the password (password) as taosdata.
Note: For native JDBC connections, taos-jdbcdriver depends on the client driver (libtaos.so on Linux; taos.dll on Windows; libtaos.dylib on macOS).
The supported common configuration parameters for native connection URLs are as follows:
/etc/taos on Linux OS, C:/TDengine/cfg on Windows OS.Using TDengine Client Driver Configuration File to Establish Connection:
When connecting to a TDengine cluster using a native JDBC connection, you can use the TDengine client driver configuration file, specifying parameters such as firstEp and secondEp in the configuration file. In this case, do not specify host and port in the JDBC URL.
Configuration such as jdbc:TAOS://:/power?user=root&password=taosdata.
In the TDengine client driver configuration file, specify firstEp and secondEp, and JDBC will use the client's configuration file to establish a connection. If the firstEp node in the cluster fails, JDBC will attempt to connect to the cluster using secondEp.
In TDengine, as long as one of the nodes in firstEp and secondEp is valid, a connection to the cluster can be established normally.
Note: The configuration file here refers to the configuration file on the machine where the application calling the JDBC Connector is located, with the default value on Linux OS being /etc/taos/taos.cfg, and on Windows OS being C://TDengine/cfg/taos.cfg.
WebSocket Connection
Using JDBC WebSocket connection does not depend on the client driver. Here's an example: jdbc:TAOS-WS://taosdemo.com:6041,taosdemo2.com:6041/power?user=root&password=taosdata&varcharAsString=true. Compared to native JDBC connections, you only need to:
For WebSocket connections, the common configuration parameters in the URL are as follows:
Note: Some configuration items (such as: locale, charset) do not take effect in WebSocket connections. WebSocket connections only support the UTF-8 character set.
In addition to obtaining a connection through a specified URL, you can also use Properties to specify parameters when establishing a connection.
All configuration parameters in Properties can also be specified in the JDBC URL. The parameter names in square brackets can be used in the JDBC URL (e.g., TSDBDriver.PROPERTY_KEY_USER[user] can be set in the JDBC URL as user=root to specify the username).
Note: The client parameter set in the application is at the process level, meaning if you need to update the client's parameters, you must restart the application. This is because the client parameter is a global parameter and only takes effect the first time it is set in the application.
The configuration parameters in properties are as follows:
Configuration Description: Used to configure basic information.
user]: Login username for TDengine, default value 'root'.password]: User login password, default value 'taosdata'.bearerToken]: bearerToken information that takes effect only when using the JDBC WebSocket connection. Its authentication priority is higher than that of username and password.batchfetch]: true: Fetch result sets in batches during query execution; false: Fetch result sets row by row. The default value is false. For historical reasons, when using a REST connection, setting this parameter to true will switch to a WebSocket connection.batchErrorIgnore]: true: Continue executing subsequent SQLs when one SQL fails during the execution of Statement's executeBatch; false: Do not execute any statements after a failed SQL. The default value is false.cfgdir]: Effective only when using native JDBC connections. Client configuration file directory path, default value on Linux OS is /etc/taos, on Windows OS is C:/TDengine/cfg.charset]: Character set used by the client, default value is the system character set.locale]: Effective only when using native JDBC connections. Client locale, default value is the current system locale.timezone]:
Configuration Description: Defines configurations such as timeout, encryption, compression and reconnection for WebSocket connections.
httpConnectTimeout]: Connection timeout, in ms, default value is 60000. Effective only under WebSocket connections.messageWaitTimeout]: Message timeout, in ms, default value is 60000. Effective only under WebSocket connections.wsKeepAlive]: The validity period of the WebSocket connection, in seconds. During this period, calling isValid will directly return the previous result. The default value is 300.useSSL]: Whether to use SSL in the connection. Effective only in WebSocket connections.disableSSLCertValidation]: Disable SSL certificate validation. Effective only when using WebSocket connections. true: enabled, false: not enabled. Default is false.enableCompression]: Whether to enable compression during transmission. Effective only when using WebSocket connections. true: enabled, false: not enabled. Default is false.enableAutoReconnect]: Whether to enable auto-reconnect. Effective only when using WebSocket connections. true: enabled, false: not enabled. Default is false.
Note: Enabling auto-reconnect is not effective for fetching result sets. Auto-reconnect is only effective for connections established through parameters specifying the database, and ineffective for later
use dbstatements to switch databases.
reconnectIntervalMs]: Auto-reconnect retry interval, in milliseconds, default value 2000. Effective only when PROPERTY_KEY_ENABLE_AUTO_RECONNECT is true.reconnectRetryCount]: Auto-reconnect retry count, default value 3, effective only when PROPERTY_KEY_ENABLE_AUTO_RECONNECT is true.Configuration Description: Extended parameters that only take effect for WebSocket connections, improving usability.
conmode]: BI mode takes effect only when the WebSocket connection is established. The default value is 0, and it can be set to 1. Setting it to 1 means enabling BI mode, where metadata information does not count sub-tables. This is mainly used in scenarios for integration with BI tools.varcharAsString]: Maps VARCHAR/BINARY types to String. Effective only when using WebSocket connections. Default value is false.app_name]: App name, can be used for display in the show connections query result. Effective only when using WebSocket connections. Default value is java.app_ip]: App IP, can be used for display in the show connections query result. Effective only when using WebSocket connections. Default value is empty.Configuration Description: Core parameters for controlling the Efficient Writing mode of WebSocket connections.
asyncWrite]: Efficient Writing mode. Currently, only the stmt method is supported. Effective only when using WebSocket connections. Default value is empty, meaning Efficient Writing mode is not enabled.backendWriteThreadNum]: In Efficient Writing mode, this refers to the number of background write threads. Effective only when using WebSocket connections. Default value is 10.batchSizeByRow]: In Efficient Writing mode, this is the batch size for writing data, measured in rows. Effective only when using WebSocket connections. Default value is 1000.cacheSizeByRow]: In Efficient Writing mode, this is the cache size, measured in rows. Effective only when using WebSocket connections. Default value is 10000.copyData]: In Efficient Writing mode, this determines whether to copy the binary data passed by the application through the addBatch method. Effective only when using WebSocket connections. Default value is false.strictCheck]: In Efficient Writing mode, this determines whether to validate the length of table names and variable-length data types. Effective only when using WebSocket connections. Default value is false.retryTimes]: In Efficient Writing mode, this is the number of retry attempts for failed write operations. Effective only when using WebSocket connections. Default value is 3.Configuration Description: Experimental parameter binding serialization mode configuration, which only takes effect for WebSocket connections and is not supported in efficient writing mode, used to optimize parameter binding performance in specific scenarios.
pbsMode]: Parameter binding serialization mode, currently an experimental feature, only supports line mode, which can improve performance when each subtable has only one piece of data in a batch of bound data. Effective only when using WebSocket connections, and not supported in Efficient Writing mode. Default value is empty.Configuration Description: Controls the active health check strategy of the driver for faulty nodes and the trigger conditions for connection rebalancing. These parameters only take effect for WebSocket connections and require auto-reconnection to be enabled.
healthCheckInitInterval]: Initial interval for active health checks (in seconds). After reaching the initial interval, it increases exponentially. Default value is 10.healthCheckMaxInterval]: Maximum interval for active health checks (in seconds). Once the exponential backoff reaches this interval, it will be used for all subsequent checks. Default value is 300.healthCheckConTimeout]: Connection timeout for health checks (in seconds). Default value is 1.healthCheckCmdTimeout]: Command timeout for health checks (in seconds). Default value is 5.healthCheckRecoveryCount]: Number of consecutive successful health check commands required to confirm node recovery. Default value is 3. Optional values: ≥ 1.healthCheckRecoveryInterval]: Interval between multiple health check commands (in seconds). Default value is 60. Optional values: ≥ 0.rebalanceThreshold]: Rebalance trigger threshold (the proportion of "the part where the current connection count exceeds the minimum connection count" to the "minimum connection count"). Rebalancing will be triggered when the threshold is reached or exceeded. Example: If rebalanceThreshold=20 (20%), it will be triggered when current ≥ min × 1.2 (e.g., triggered when the minimum is 100 connections and the current is ≥ 120). Default value is 20. Optional values: 10-50.rebalanceConBaseCount]: The minimum total number of connections required to trigger rebalancing. Rebalancing will not be performed if the total connection count is less than this value. Default value is 30.Priority of Configuration Parameters:
When obtaining connections through the three methods mentioned earlier, if configuration parameters are duplicated in the URL, Properties, and client configuration file, the priority from high to low is as follows:
For example: if the password is specified as taosdata in the URL and as taosdemo in the Properties, then JDBC will use the password from the URL to establish the connection.
Connection connect(String url, java.util.Properties info) throws SQLException
url: Connection address URL, see above for URL specifications.info: Connection properties, see above for Properties section.SQLException if the connection fails.boolean acceptsURL(String url) throws SQLException
url: Connection address URL.true: supported, false: not supported.SQLException if the URL is illegal.DriverPropertyInfo[] getPropertyInfo(String url, java.util.Properties info) throws SQLException
url: A String parameter representing the database URL.info: A java.util.Properties parameter containing a list of properties that might be provided by the user when attempting to connect.DriverPropertyInfo[], an array of DriverPropertyInfo objects. Each DriverPropertyInfo object contains detailed information about a specific database connection property.SQLException if a database access error or other error occurs during the retrieval of property information.int getMajorVersion()
int getMinorVersion()
DatabaseMetaData is part of the JDBC API, providing detailed information about the database's metadata, where metadata means data about data. Through the DatabaseMetaData interface, you can query detailed information about the database server, such as the database product name, version, installed features, list of tables, views, stored procedures, etc. This is very useful for understanding and adapting to the characteristics of different databases.
String getURL() throws SQLException
SQLException if the retrieval fails.String getUserName() throws SQLException
SQLException if the retrieval fails.String getDriverName() throws SQLException
SQLException if the retrieval fails.String getDriverVersion() throws SQLException
SQLException if the retrieval fails.int getDriverMajorVersion()
int getDriverMinorVersion()
String getDatabaseProductName() throws SQLException
String getDatabaseProductVersion() throws SQLException
String getIdentifierQuoteString() throws SQLException
String getSQLKeywords() throws SQLException
String getNumericFunctions() throws SQLException
String getStringFunctions() throws SQLException
String getSystemFunctions() throws SQLException
String getTimeDateFunctions() throws SQLException
String getCatalogTerm() throws SQLException
String getCatalogSeparator() throws SQLException
int getDefaultTransactionIsolation() throws SQLException
boolean supportsTransactionIsolationLevel(int level) throws SQLException
level: Transaction isolation level.true: supported, false: not supported.SQLException if the operation fails.ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String[] types) throws SQLException
catalog: Catalog name; null means no catalog specified.schemaPattern: Pattern for the schema name; null means no schema specified.tableNamePattern: Pattern for the table name.types: List of table types, returns tables of specified types.ResultSet containing table information.SQLException if the operation fails.ResultSet getCatalogs() throws SQLException
ResultSet containing catalog information.SQLException if the operation fails.ResultSet getTableTypes() throws SQLException
ResultSet containing table types.SQLException if the operation fails.ResultSet getColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern) throws SQLException
catalog: Catalog name; null means no catalog specified.schemaPattern: Pattern for the schema name; null means no schema specified.tableNamePattern: Pattern for the table name.columnNamePattern: Pattern for the column name.ResultSet containing column information.SQLException if operation fails.ResultSet getPrimaryKeys(String catalog, String schema, String table) throws SQLException
catalog: Catalog name; null means no catalog specified.schema: Schema name; null means no schema specified.table: Table name.ResultSet containing primary key information.SQLException if operation fails.Connection getConnection() throws SQLException
Connection object.SQLException if connection retrieval fails.ResultSet getSuperTables(String catalog, String schemaPattern, String tableNamePattern) throws SQLException
catalog: Catalog name; null means no catalog specified.schemaPattern: Pattern for the schema name; null means no schema specified.tableNamePattern: Pattern for the table name.ResultSet containing parent table information.SQLException if operation fails.boolean supportsResultSetHoldability(int holdability) throws SQLException
ResultSet holdability.holdability: Holdability of the ResultSet.true if supported, false if not.SQLException if operation fails.int getSQLStateType() throws SQLException
SQLException if operation fails.List of interface methods that return true for supported features, others not explicitly mentioned return false.
| Interface Method | Description |
|---|---|
boolean nullsAreSortedAtStart() | Determines if NULL values are sorted at the start |
boolean storesLowerCaseIdentifiers() | Determines if the database stores identifiers in lowercase |
boolean supportsAlterTableWithAddColumn() | Determines if the database supports adding columns with ALTER TABLE |
boolean supportsAlterTableWithDropColumn() | Determines if the database supports dropping columns with ALTER TABLE |
boolean supportsColumnAliasing() | Determines if the database supports column aliasing |
boolean supportsGroupBy() | Determines if the database supports GROUP BY statements |
boolean isCatalogAtStart() | Determines if the catalog name appears at the start of the fully qualified name in the database |
boolean supportsCatalogsInDataManipulation() | Determines if the database supports catalog names in data manipulation statements |
The JDBC driver supports creating connections, returning objects that support the JDBC standard Connection interface, and also provides the AbstractConnection interface, which expands some schema-less write interfaces.
Statement createStatement() throws SQLException
Statement object to execute SQL statements. For a detailed description of the Statement interface, see the section below on executing SQL.Statement object.SQLException if the operation fails.PreparedStatement prepareStatement(String sql) throws SQLException
PreparedStatement object to execute the given SQL statement. For a detailed description of the PreparedStatement interface, see the section below on executing SQL.sql: The precompiled SQL statement.PreparedStatement object.SQLException if the operation fails.String nativeSQL(String sql) throws SQLException
sql: The SQL statement to convert.SQLException if the operation fails.void close() throws SQLException
SQLException if the operation fails.boolean isClosed() throws SQLException
true: closed, false: not closed.SQLException if the operation fails.DatabaseMetaData getMetaData() throws SQLException
SQLException if the operation fails.void setCatalog(String catalog) throws SQLException
catalog: The name of the database to set.SQLException if the operation fails.String getCatalog() throws SQLException
SQLException if the operation fails.Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException
Statement object, specifying the ResultSet type and concurrency mode.resultSetType: The ResultSet type.resultSetConcurrency: The concurrency mode.Statement object.SQLException if the operation fails.Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException
Statement object, specifying the ResultSet type, concurrency mode, and holdability.resultSetType: The ResultSet type.resultSetConcurrency: The concurrency mode.resultSetHoldability: The holdability.Statement object.SQLException if the operation fails.PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException
PreparedStatement object, specifying the SQL, ResultSet type, and concurrency mode.sql: The precompiled SQL statement.resultSetType: The ResultSet type.resultSetConcurrency: The concurrency mode.PreparedStatement object.SQLException if the operation fails.PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException
PreparedStatement object, specifying the SQL, ResultSet type, concurrency mode, and holdability.sql: The precompiled SQL statement.resultSetType: The ResultSet type.resultSetConcurrency: The concurrency mode.resultSetHoldability: The holdability.PreparedStatement object.SQLException if the operation fails.PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException
PreparedStatement object, specifying the SQL statement and the flag for auto-generated keys.sql: The precompiled SQL statement.autoGeneratedKeys: The flag indicating whether auto-generated keys should be produced.PreparedStatement object.SQLException if the operation fails.void setHoldability(int holdability) throws SQLException
ResultSet objects.holdability: The holdability of the ResultSet.SQLException if the operation fails.int getHoldability() throws SQLException
ResultSet objects.ResultSet.SQLException if the operation fails.boolean isValid(int timeout) throws SQLException
timeout: The timeout in seconds for the validity check.true: connection is valid, false: connection is invalid.SQLException if the operation fails.void setClientInfo(String name, String value) throws SQLClientInfoException
name: The property name.value: The property value.SQLClientInfoException if setting fails.void setClientInfo(Properties properties) throws SQLClientInfoException
properties: The properties collection.SQLClientInfoException if setting fails.String getClientInfo(String name) throws SQLException
name: The property name.SQLException if the operation fails.Properties getClientInfo() throws SQLException
Properties object containing all client information properties.SQLException if the operation fails.Note: The abstract type interfaces below will be implemented by specific implementation classes, so the connection object obtained after establishing a connection can be directly called.
abstract void write(String[] lines, SchemalessProtocolType protocolType, SchemalessTimestampType timestampType, Integer ttl, Long reqId) throws SQLException
lines: Array of data lines to be written.protocolType: Protocol type: supports InfluxDB LINE, OpenTSDB TELNET, OpenTSDB JSON.timestampType: Timestamp type, supports HOURS, MINUTES, SECONDS, MILLI_SECONDS, MICRO_SECONDS, and NANO_SECONDS.ttl: Data's time to live, in days.reqId: Request ID.void write(String[] lines, SchemalessProtocolType protocolType, SchemalessTimestampType timestampType) throws SQLException
lines: Array of data lines to be written.protocolType: Protocol type: supports InfluxDB LINE, OpenTSDB TELNET, OpenTSDB JSON.timestampType: Timestamp type, supports HOURS, MINUTES, SECONDS, MILLI_SECONDS, MICRO_SECONDS, and NANO_SECONDS.void write(String line, SchemalessProtocolType protocolType, SchemalessTimestampType timestampType) throws SQLException
line: Data line to be written.protocolType: Protocol type: supports InfluxDB LINE, OpenTSDB TELNET, OpenTSDB JSON.timestampType: Timestamp type, supports HOURS, MINUTES, SECONDS, MILLI_SECONDS, MICRO_SECONDS, and NANO_SECONDS.void write(List<String> lines, SchemalessProtocolType protocolType, SchemalessTimestampType timestampType) throws SQLException
lines: List of data lines to be written.protocolType: Protocol type: supports InfluxDB LINE, OpenTSDB TELNET, OpenTSDB JSON.timestampType: Timestamp type, supports HOURS, MINUTES, SECONDS, MILLI_SECONDS, MICRO_SECONDS, and NANO_SECONDS.int writeRaw(String line, SchemalessProtocolType protocolType, SchemalessTimestampType timestampType) throws SQLException
line: Raw data to be written.protocolType: Protocol type: supports InfluxDB LINE, OpenTSDB TELNET, OpenTSDB JSON.timestampType: Timestamp type, supports HOURS, MINUTES, SECONDS, MILLI_SECONDS, MICRO_SECONDS, and NANO_SECONDS.abstract int writeRaw(String line, SchemalessProtocolType protocolType, SchemalessTimestampType timestampType, Integer ttl, Long reqId) throws SQLException
line: Raw data to be written.protocolType: Protocol type: supports InfluxDB LINE, OpenTSDB TELNET, OpenTSDB JSON.timestampType: Timestamp type, supports HOURS, MINUTES, SECONDS, MILLI_SECONDS, MICRO_SECONDS, and NANO_SECONDS.ttl: Data's time to live, in days.reqId: Request ID.The JDBC driver provides a JDBC-compliant Statement interface that supports the following features:
Statement interface is primarily used to execute static SQL statements and return the results they generate.SELECT statements).INSERT, UPDATE, DELETE, etc.ResultSet object) returned after query execution and traverse the returned data.Statement object to release database resources.Additionally, the JDBC driver also provides an extended interface for request link tracking.
ResultSet executeQuery(String sql) throws SQLException
ResultSet object.sql: The SQL query statement to execute.ResultSet.SQLException will be thrown.int executeUpdate(String sql) throws SQLException
INSERT or DELETE statement, or a SQL statement that does not return any content.sql: The SQL update statement to execute.SQLException will be thrown.void close() throws SQLException
Statement object.SQLException will be thrown.int getMaxFieldSize() throws SQLException
ResultSet object.SQLException will be thrown.int getQueryTimeout() throws SQLException
Statement object.SQLException will be thrown.void setQueryTimeout(int seconds) throws SQLException
Statement object.seconds: Query timeout in seconds.SQLException will be thrown.boolean execute(String sql) throws SQLException
sql: The SQL statement to execute.true indicates that the result is a ResultSet object; false indicates that the result is an update count or there is no result.SQLException will be thrown.ResultSet getResultSet() throws SQLException
ResultSet object generated by the current Statement object.Statement object.SQLException will be thrown.int getUpdateCount() throws SQLException
Statement object.ResultSet object or there are no results.SQLException if a database access error or other error occurs during retrieval.boolean getMoreResults() throws SQLException
Statement object to check if it is a ResultSet object.true if the next result is a ResultSet object; false if the next result is an update count or there are no more results.SQLException if a database access error or other error occurs during the move.int getFetchDirection() throws SQLException
Statement object fetches rows from the database.FETCH_FORWARD direction.SQLException if a database access error or other error occurs during retrieval.void setFetchSize(int rows) throws SQLException
rows: The number of rows to fetch at a time.SQLException if a database access error or other error occurs during setting.int getFetchSize() throws SQLException
Statement object.SQLException if a database access error or other error occurs during retrieval.int getResultSetConcurrency() throws SQLException
ResultSet object.ResultSet object.SQLException if a database access error or other error occurs during retrieval.int getResultSetType() throws SQLException
ResultSet object.ResultSet object.SQLException if a database access error or other error occurs during retrieval.void addBatch(String sql) throws SQLException
Statement object's batch.sql: The SQL statement to be added to the batch.SQLException if a database access error or other error occurs during addition.void clearBatch() throws SQLException
Statement object.SQLException if a database access error or other error occurs during clearing.int[] executeBatch() throws SQLException
SQLException if a database access error or other error occurs during execution.Connection getConnection() throws SQLException
Connection object that produced this Statement object.Statement object.SQLException if a database access error or other error occurs during retrieval.int getResultSetHoldability() throws SQLException
ResultSet object.ResultSet object.SQLException will be thrown.boolean isClosed() throws SQLException
Statement object is closed.true if this Statement object is closed; false if it is not.SQLException will be thrown.Extended interfaces are mainly used for request link tracing.
ResultSet executeQuery(String sql, Long reqId) throws SQLException
sql: The SQL query statement to execute.reqId: Request id.ResultSet object containing the query results.SQLException will be thrown.int executeUpdate(String sql, Long reqId) throws SQLException
sql: The SQL update statement to execute.reqId: Request id.SQLException will be thrown.boolean execute(String sql, Long reqId) throws SQLException
sql: The SQL statement to execute.reqId: Request id.true if the first result is a ResultSet object; false if it is an update count or there are no results.SQLException will be thrown.The JDBC driver supports the standard ResultSet interface and the corresponding ResultSetMetaData interface, providing methods for reading metadata and data from the result set.
The JDBC driver supports the standard ResultSet interface, providing methods for reading metadata and data from the result set.
ResultSetMetaData getMetaData() throws SQLException
boolean next() throws SQLException
true if the new current row is valid; false if there are no more rows in the result set.void close() throws SQLException
boolean wasNull() throws SQLException
true if the last column value read was NULL; otherwise, false.String getString(int columnIndex) throws SQLException
columnIndex: The column number, with the first column being 1, the second being 2, and so on.boolean getBoolean(int columnIndex) throws SQLException
columnIndex: The column number.true if the specified column's value is true; false if the value is false or NULL.byte getByte(int columnIndex) throws SQLException
columnIndex: The column number.short getShort(int columnIndex) throws SQLException
columnIndex: The column number.int getInt(int columnIndex) throws SQLException
columnIndex: The column number.long getLong(int columnIndex) throws SQLException
columnIndex: The column number.float getFloat(int columnIndex) throws SQLException
columnIndex: The column number.double getDouble(int columnIndex) throws SQLException
columnIndex: The column number.byte[] getBytes(int columnIndex) throws SQLException
columnIndex: The column number.SQLException will be thrown.Date getDate(int columnIndex) throws SQLException
java.sql.Date object.columnIndex: The column number.SQLException will be thrown.Time getTime(int columnIndex) throws SQLException
java.sql.Time object.columnIndex: The column number.SQLException will be thrown.Timestamp getTimestamp(int columnIndex) throws SQLException
java.sql.Timestamp.columnIndex: The column number.SQLException will be thrown.String getNString(int columnIndex) throws SQLException
columnIndex: The column number (starting from 1).SQLException will be thrown.Object getObject(int columnIndex) throws SQLException
columnIndex: The column number.SQLException will be thrown.String getString(String columnLabel) throws SQLException
columnLabel: The column label name.SQLException will be thrown.boolean getBoolean(String columnLabel) throws SQLException
columnLabel: The column label name.true if the specified column name's value is true; if the value is false or NULL, returns false.SQLException will be thrown.byte getByte(String columnLabel) throws SQLException
columnLabel: The column label name.SQLException will be thrown.short getShort(String columnLabel) throws SQLException
columnLabel: The column label name.SQLException will be thrown.int getInt(String columnLabel) throws SQLException
columnLabel: The column label name.SQLException will be thrown.long getLong(String columnLabel) throws SQLException
columnLabel: The column label name.SQLException will be thrown.float getFloat(String columnLabel) throws SQLException
columnLabel: The column label name.SQLException will be thrown.double getDouble(String columnLabel) throws SQLException
columnLabel: The column label name.SQLException will be thrown.byte[] getBytes(String columnLabel) throws SQLException
columnLabel: The label of the column.SQLException will be thrown.Date getDate(String columnLabel) throws SQLException
java.sql.Date object.columnLabel: The label of the column.SQLException will be thrown.Time getTime(String columnLabel) throws SQLException
java.sql.Time object.columnLabel: The label of the column.SQLException will be thrown.Timestamp getTimestamp(String columnLabel) throws SQLException
java.sql.Timestamp.columnLabel: The label of the column.SQLException will be thrown.String getNString(String columnLabel) throws SQLException
columnLabel: The label of the column whose value is to be retrieved.SQLException will be thrown.Object getObject(String columnLabel) throws SQLException
columnLabel: The label of the column.SQLException will be thrown.int findColumn(String columnLabel) throws SQLException
columnLabel: The label of the column.SQLException will be thrown.boolean isBeforeFirst() throws SQLException
SQLException will be thrown.boolean isAfterLast() throws SQLException
SQLException will be thrown.boolean isFirst() throws SQLException
SQLException will be thrown.boolean isLast() throws SQLException
SQLException if a database access error occurs.int getRow() throws SQLException
SQLException if a database access error occurs.void setFetchSize(int rows) throws SQLException
rows: The specified number of rows to fetch. If set to 0, the driver's default value is used.SQLException if the result set is closed or if the rows parameter is less than 0.int getFetchSize() throws SQLException
SQLException if the result set is closed.int getType() throws SQLException
ResultSet.ResultSet. Always returns ResultSet.TYPE_FORWARD_ONLY, indicating that the result set cursor can only move forward.SQLException if the result set is closed.int getConcurrency() throws SQLException
ResultSet.ResultSet. Always returns ResultSet.CONCUR_READ_ONLY, indicating that the result set cannot be updated.SQLException if the result set is closed.<T> T getObject(String columnLabel, Class<T> type) throws SQLException
columnLabel: The label name of the column whose value is to be retrieved.type: The Class object of the expected return type in Java.SQLException if a database access error occurs or if the specified type conversion is not supported.ResultSetMetaData provides interfaces to obtain result set metadata. A ResultSetMetaData type object is obtained through the getMetaData interface of a ResultSet type object.
int getColumnCount() throws SQLException
boolean isSearchable(int column) throws SQLException
column: The column number (starting from 1).int isNullable(int column) throws SQLException
column: The column number (starting from 1).ResultSetMetaData.columnNoNulls, ResultSetMetaData.columnNullable, or ResultSetMetaData.columnNullableUnknown.boolean isSigned(int column) throws SQLException
column: The column number (starting from 1).int getColumnDisplaySize(int column) throws SQLException
column: The column number (starting from 1).SQLException if the column index is out of range.String getColumnLabel(int column) throws SQLException
column: The column number (starting from 1).SQLException if the column index is out of range.String getColumnName(int column) throws SQLException
column: The column number (starting from 1).SQLException if the column index is out of range.int getPrecision(int column) throws SQLException
column: The column number (starting from 1).SQLException if the column index is out of range.int getScale(int column) throws SQLException
column: The column number (starting from 1).SQLException if the column index is out of range.String getTableName(int column) throws SQLException
column: The column number (starting from 1).String getCatalogName(int column) throws SQLException
column: The column number (starting from 1).int getColumnType(int column) throws SQLException
column: The column number (starting from 1).java.sql.Types.String getColumnTypeName(int column) throws SQLException
column: The column number (starting from 1).boolean isReadOnly(int column) throws SQLException
column: The column number (starting from 1).String getColumnClassName(int column) throws SQLException
column: The column number (starting from 1).PreparedStatement allows the use of precompiled SQL statements, which can enhance performance and provide the capability of parameterized queries, thereby increasing security.
The JDBC driver provides two classes that implement the PreparedStatement interface:
Since the JDBC standard does not have a high-performance data binding interface, both TSDBPreparedStatement and TSWSPreparedStatement have added some methods to extend the parameter binding capabilities.
Note: Since PreparedStatement inherits the Statement interface, the repeated interfaces are not described again here, please refer to the corresponding descriptions in the Statement interface.
void setNull(int parameterIndex, int sqlType) throws SQLException
parameterIndex: An int type parameter, indicating the parameter index position in the precompiled statement.sqlType: An int type parameter, indicating the SQL type to be set to NULL.void setBoolean(int parameterIndex, boolean x) throws SQLException
parameterIndex: An int type parameter, indicating the parameter index position in the precompiled statement.x: A boolean type parameter, indicating the value to be set.void setByte(int parameterIndex, byte x) throws SQLExceptionvoid setShort(int parameterIndex, short x) throws SQLExceptionvoid setInt(int parameterIndex, int x) throws SQLExceptionvoid setLong(int parameterIndex, long x) throws SQLExceptionvoid setFloat(int parameterIndex, float x) throws SQLExceptionvoid setDouble(int parameterIndex, double x) throws SQLExceptionvoid setBigDecimal(int parameterIndex, BigDecimal x) throws SQLExceptionvoid setString(int parameterIndex, String x) throws SQLExceptionvoid setBytes(int parameterIndex, byte[] x) throws SQLExceptionvoid setDate(int parameterIndex, Date x) throws SQLExceptionvoid setTime(int parameterIndex, Time x) throws SQLExceptionvoid setTimestamp(int parameterIndex, Timestamp x) throws SQLExceptionvoid clearParameters() throws SQLException
void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException
parameterIndex: An int type parameter, indicating the parameter index position in the precompiled statement.x: An Object type parameter, indicating the value to be set.targetSqlType: An int type parameter, indicating the SQL type of the x parameter.void setObject(int parameterIndex, Object x) throws SQLException
parameterIndex: An int type parameter, indicating the parameter index position in the precompiled statement.x: An Object type parameter, indicating the value to be set.ResultSetMetaData getMetaData() throws SQLException
ParameterMetaData getParameterMetaData() throws SQLException
ParameterMetaData provides a parameter metadata interface:
int getParameterCount() throws SQLException
int.SQLException will be thrown.boolean isSigned(int param) throws SQLException
param: The index of the parameter, type int.true if the parameter is signed; otherwise, returns false.SQLException will be thrown.int getPrecision(int param) throws SQLException
param: The index of the parameter, type int.int.SQLException will be thrown.int getScale(int param) throws SQLException
param: The index of the parameter, type int.int.SQLException will be thrown.int getParameterType(int param) throws SQLException
param: The index of the parameter, type int.int.SQLException will be thrown.String getParameterTypeName(int param) throws SQLException
param: The index of the parameter, type int.String.SQLException will be thrown.String getParameterClassName(int param) throws SQLException
param: The index of the parameter, type int.String.SQLException will be thrown.int getParameterMode(int param) throws SQLException
param: The index of the parameter, type int.int.SQLException will be thrown.void setTableName(String name) throws SQLException
name: A String type parameter representing the table name to bind.void setTagNull(int index, int type)
index: The index position of the tag.type: The data type of the tag.void setTagBoolean(int index, boolean value)
index: The index position of the tag.value: The boolean value to set.The following interfaces are similar to setTagBoolean, with different value types to set, and are not described further:
void setTagInt(int index, int value)void setTagByte(int index, byte value)void setTagShort(int index, short value)void setTagLong(int index, long value)void setTagTimestamp(int index, long value)void setTagFloat(int index, float value)void setTagDouble(int index, double value)void setTagString(int index, String value)void setTagNString(int index, String value)void setTagJson(int index, String value)void setTagVarbinary(int index, byte[] value)void setTagGeometry(int index, byte[] value)void setInt(int columnIndex, ArrayList<Integer> list) throws SQLException
columnIndex: The index position of the column.list: A list containing integer values.The following interfaces are the same as setInt except for the type of value to be set:
void setFloat(int columnIndex, ArrayList<Float> list) throws SQLExceptionvoid setTimestamp(int columnIndex, ArrayList<Long> list) throws SQLExceptionvoid setLong(int columnIndex, ArrayList<Long> list) throws SQLExceptionvoid setDouble(int columnIndex, ArrayList<Double> list) throws SQLExceptionvoid setBoolean(int columnIndex, ArrayList<Boolean> list) throws SQLExceptionvoid setByte(int columnIndex, ArrayList<Byte> list) throws SQLExceptionvoid setShort(int columnIndex, ArrayList<Short> list) throws SQLExceptionvoid setString(int columnIndex, ArrayList<String> list, int size) throws SQLException
columnIndex: The index position of the column.list: A list containing string values.size: The maximum length of all strings, generally the limit value of the table creation statement.The following interfaces are the same as setString except for the type of value to be set:
void setVarbinary(int columnIndex, ArrayList<byte[]> list, int size) throws SQLExceptionvoid setGeometry(int columnIndex, ArrayList<byte[]> list, int size) throws SQLExceptionvoid setNString(int columnIndex, ArrayList<String> list, int size) throws SQLExceptionvoid columnDataAddBatch() throws SQLException
setInt(int columnIndex, ArrayList<Integer> list) to the current PrepareStatement object's batch.void columnDataExecuteBatch() throws SQLException
JDBC standards do not support data subscription, therefore all interfaces in this chapter are extension interfaces. The TaosConsumer class provides consumer-related interfaces, ConsumerRecord provides consumption record-related interfaces, TopicPartition and OffsetAndMetadata provide partition information and offset metadata interfaces. Finally, ReferenceDeserializer and MapDeserializer provide support for deserialization.
TaosConsumer(Properties properties) throws SQLException
properties: A set of properties, see below for detailed supported properties.Consumer support property list:
ip:port where taosAdapter is located. Multiple endpoints are supported, separated by commas, such as ip1:port1,ip2:port2. If the connection is disconnected during the poll process, it can switch to other nodes (requires setting the auto-reconnect parameter TSDBDriver.PROPERTY_KEY_ENABLE_AUTO_RECONNECT to true).ip:port where the TDengine TSDB server is located. Native connections do not support multiple endpoints.com.taosdata.jdbc.tmq.ReferenceDeserializer, specify the result set bean, and implement deserialization. You can also inherit com.taosdata.jdbc.tmq.Deserializer and customize the deserialization method based on the SQL resultSet. When subscribing to a database, you need to set value.deserializer to com.taosdata.jdbc.tmq.MapEnhanceDeserializer when creating a consumer, and then create a consumer of type TaosConsumer<TMQEnhMap>. This way, each row of data can be deserialized into a table name and a Map.For other parameters, please refer to: Consumer parameter list, note that the default value of auto.offset.reset in message subscription has changed starting from TDengine server version 3.2.0.0.
void subscribe(Collection<String> topics) throws SQLException
topics: A Collection<String> type parameter, representing the list of topics to subscribe to.void unsubscribe() throws SQLException
Set<String> subscription() throws SQLException
Set<String>, which is the collection of all currently subscribed topics.ConsumerRecords<V> poll(Duration timeout) throws SQLException
timeout: A Duration type parameter, representing the polling timeout.ConsumerRecords<V>, which are the polled message records.void commitAsync() throws SQLException
void commitSync() throws SQLException
void close() throws SQLException
void seek(TopicPartition partition, long offset) throws SQLException
partition: A TopicPartition type parameter, representing the partition to operate on.offset: A long type parameter, representing the offset to set.long position(TopicPartition tp) throws SQLException
tp: A TopicPartition type parameter, representing the partition to query.long, which is the current offset of the given partition.Map<TopicPartition, Long> beginningOffsets(String topic) throws SQLException
topic: A String type parameter, representing the topic to query.Map<TopicPartition, Long>, which are the earliest offsets for each partition of the specified topic.Map<TopicPartition, Long> endOffsets(String topic) throws SQLException
topic: A String type parameter, representing the topic to query.Map<TopicPartition, Long>, which are the latest offsets for each partition of the specified topic.void seekToBeginning(Collection<TopicPartition> partitions) throws SQLException
partitions: A Collection<TopicPartition> type parameter, representing the set of partitions to operate on.void seekToEnd(Collection<TopicPartition> partitions) throws SQLException
partitions: A Collection<TopicPartition> type parameter, representing the set of partitions to operate on.Set<TopicPartition> assignment() throws SQLException
Set<TopicPartition>, which are all partitions currently assigned to the consumer.OffsetAndMetadata committed(TopicPartition partition) throws SQLException
partition: A TopicPartition type parameter, representing the partition to query.OffsetAndMetadata, which is the last committed offset of the specified partition.Map<TopicPartition, OffsetAndMetadata> committed(Set<TopicPartition> partitions) throws SQLException
partitions: A Set<TopicPartition> type parameter, representing the set of partitions to query.Map<TopicPartition, OffsetAndMetadata>, which are the last committed offsets of the set of partitions.The ConsumerRecords class provides consumption record information, allowing iteration over ConsumerRecord objects.
ConsumerRecord provides the following interfaces:
String getTopic()
String, which is the message topic.String getDbName()
String, which is the database name.int getVGroupId()
int, which is the virtual group ID.V value()
V, which is the message value.long getOffset()
long, which is the message offset.The TopicPartition class provides partition information, including the message topic and virtual group ID.
TopicPartition(String topic, int vGroupId)
topic: A String type parameter representing the message topic.vGroupId: An int type parameter representing the virtual group ID.String getTopic()
String, which is the topic of this TopicPartition instance.int getVGroupId()
int, which is the virtual group ID of this TopicPartition instance.The OffsetAndMetadata class provides offset metadata information.
long offset()
long, which is the offset in this OffsetAndMetadata instance.String metadata()
String, which is the metadata in this OffsetAndMetadata instance.The JDBC driver provides two deserialization classes: ReferenceDeserializer and MapDeserializer. Both implement the Deserializer interface.
ReferenceDeserializer is used to deserialize a consumed record into an object, ensuring that the object class's property names correspond to the consumed data's column names and that the types match.
MapDeserializer will deserialize a consumed row of data into a Map<String, Object> object, with keys as column names and values as Java objects.
Interfaces of ReferenceDeserializer and MapDeserializer are not directly called by users, please refer to usage examples.
JDBC Javadoc: JDBC Reference doc