Use SQL queries with a direct JDBC connection

更新时间:
复制 MD 格式

Connect directly to a Tablestore instance and run SQL queries through the standard JDBC interface with the com.aliyun.openservices:tablestore-jdbc driver.

Prerequisites

  • An AccessKey pair (RAM users require the "Action": "ots:SQL*" permission)

  • A data table and its mapping table (DDL operations)

Step 1: Install the JDBC driver

The driver is available as a Maven dependency or a standalone JAR.

Maven dependency

Add the Tablestore JDBC driver dependency to the <dependencies> section of your Maven pom.xml. The following example uses version 5.17.0:

<dependency>
  <groupId>com.aliyun.openservices</groupId>
  <artifactId>tablestore-jdbc</artifactId>
  <version>5.17.0</version>
</dependency>

Manual installation

Download the Tablestore JDBC driver and import it into your project.

Step 2: Use a direct JDBC connection

Load the driver, connect to an instance, and then run SQL statements.

  1. Load the Tablestore JDBC driver with Class.forName().

    The driver class name is com.alicloud.openservices.tablestore.jdbc.OTSDriver.

    Class.forName("com.alicloud.openservices.tablestore.jdbc.OTSDriver");
  2. Connect to a Tablestore instance with JDBC.

    String url = "jdbc:ots:https://myinstance.cn-hangzhou.ots.aliyuncs.com/myinstance";
    String user = "************************";
    String password = "********************************";
    Connection conn = DriverManager.getConnection(url, user, password);

    The following table describes the connection parameters.

    Parameter

    Description

    url

    The Tablestore JDBC URL. Format: jdbc:ots:schema://[accessKeyId:accessKeySecret@]endpoint/instanceName[?param1=value1&...&paramN=valueN]. The URL fields are:

    • schema (required): The protocol. Set this field to https.

    • accessKeyId:accessKeySecret (optional): The AccessKey ID and AccessKey Secret of your Alibaba Cloud account or RAM user.

    • endpoint (required): The endpoint of the instance.

    • instanceName (required): The name of the instance.

    For other configuration items, see Configuration.

    user

    The AccessKey ID of your Alibaba Cloud account or RAM user.

    password

    The AccessKey Secret of your Alibaba Cloud account or RAM user.

    Pass your AccessKey pair and settings through the URL or a Properties object. The following examples connect to the myinstance instance in the China (Hangzhou) region over the Internet.

    URL

    DriverManager.getConnection("jdbc:ots:https://************************:********************************@myinstance.cn-hangzhou.ots.aliyuncs.com/myinstance?enableRequestCompression=true");

    Properties

    Properties info = new Properties();
    info.setProperty("user", "************************");
    info.setProperty("password", "********************************");
    info.setProperty("enableRequestCompression", "true");
    DriverManager.getConnection("jdbc:ots:https://myinstance.cn-hangzhou.ots.aliyuncs.com/myinstance", info);
  3. Run SQL statements.

    Use createStatement or prepareStatement to run queries.

    createStatement

    String sql = "SELECT pk1, col_a FROM test_table";
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery(sql);
    while (rs.next()) {
        System.out.println(rs.getString("pk1") + ", " + rs.getLong("col_a"));
    }
    rs.close();
    stmt.close();

    prepareStatement

    String sql = "SELECT * FROM test_table WHERE pk = ?";
    PreparedStatement stmt = conn.prepareStatement(sql);
    stmt.setLong(1, 1);
    ResultSet rs = stmt.executeQuery();
    ResultSetMetaData meta = rs.getMetaData();
    while (rs.next()) {
        for (int i = 1; i <= meta.getColumnCount(); i++) {
            System.out.println(meta.getColumnName(i) + " = " + rs.getString(i));
        }
    }
    rs.close();
    stmt.close();

Complete example

The following example queries data from test_table in a Tablestore instance.

public class Demo {
    public static void main(String[] args) throws Exception {
        Class.forName("com.alicloud.openservices.tablestore.jdbc.OTSDriver");

        String url = "jdbc:ots:https://myinstance.cn-hangzhou.ots.aliyuncs.com/myinstance";
        String user = "************************";
        String password = "********************************";
        Connection conn = DriverManager.getConnection(url, user, password);

        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM test_table");
        ResultSetMetaData meta = rs.getMetaData();
        int colCount = meta.getColumnCount();
        while (rs.next()) {
            for (int i = 1; i <= colCount; i++) {
                System.out.print(meta.getColumnName(i) + "=" + rs.getString(i) + "\t");
            }
            System.out.println();
        }

        rs.close();
        stmt.close();
        conn.close();
    }
}

Configuration

The Tablestore JDBC driver is built on the Java SDK and supports configuration through URL parameters or Properties.

Important

The server-side timeout for SQL requests is 30 seconds. To set a shorter timeout, set syncClientWaitFutureTimeoutInMillis to a value less than 30000, or call setQueryTimeout on each Statement.

Parameter

Default

Description

enableRequestCompression

false

Specifies whether to compress request data.

enableResponseCompression

false

Specifies whether to compress response data.

ioThreadCount

2

The number of IOReactor threads in the HttpAsyncClient.

maxConnections

300

The maximum number of HTTP connections.

socketTimeoutInMillisecond

30000

The timeout for data transfer at the socket layer. Unit: milliseconds. A value of 0 means no timeout.

connectionTimeoutInMillisecond

30000

The timeout for establishing a connection. Unit: milliseconds. A value of 0 means no timeout.

retryThreadCount

1

The number of threads in the retry thread pool.

syncClientWaitFutureTimeoutInMillis

-1

The timeout for asynchronous wait. Unit: milliseconds.

connectionRequestTimeoutInMillisecond

60000

The timeout for sending a request. Unit: milliseconds.

retryStrategy

default

The retry policy. Valid values:

  • disable: No retry.

  • default: Retries on OTSNotEnoughCapacityUnit, OTSTableNotReady, OTSPartitionUnavailable, OTSServerBusy, OTSQuotaExhausted, OTSTimeout, OTSInternalServerError, and OTSServerUnavailable errors until timeout.

retryTimeout

10

The retry timeout value and time unit. Valid time units:

  • seconds

  • milliseconds

  • microseconds

  • nanoseconds

  • minutes

  • hours

retryTimeoutUnit

seconds

Data type conversion

Tablestore supports five data types: Integer, Double, String, Binary, and Boolean. The JDBC driver automatically converts between Java types and Tablestore data types.

Java to Tablestore

When you set SQL parameters with PreparedStatement, the driver supports Byte, Short, Int, Long, BigDecimal, Float, Double, String, CharacterStream, Bytes, and Boolean types.

PreparedStatement stmt = conn.prepareStatement("SELECT * FROM t WHERE pk = ?");
stmt.setLong(1, 1);                                // Supported
stmt.setURL(1, new URL("https://aliyun.com/"));    // Not supported — throws an exception

Tablestore to Java

When you read results from a ResultSet, the JDBC driver automatically converts data types according to the following rules.

Tablestore type

Conversion rules

Integer

  • Conversion to an integer type throws an exception if the value is out of range.

  • Conversion to a floating-point type may lose precision.

  • Conversion to a string or binary type is equivalent to toString().

  • Conversion to a boolean type returns true for non-zero values.

Double

String

  • Conversion to an integer or floating-point type throws an exception if parsing fails.

  • Conversion to a boolean type returns true if the string is "true".

Binary

Boolean

  • Conversion to an integer or floating-point type returns 1 for true and 0 for false.

  • Conversion to a string or binary type is equivalent to toString().

Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT count(*) FROM t");
while (rs.next()) {
    rs.getLong(1);               // Supported
    rs.getCharacterStream(1);    // Not supported — throws an exception
}

The following table shows which conversions between Tablestore data types and Java types are supported.

Note

"✓" indicates normal conversion, "~" indicates possible exception, and "×" indicates unsupported conversion.

Type

Integer

Double

String

Binary

Boolean

Byte

Short

Int

Long

BigDecimal

Float

Double

String

CharacterStream

×

×

×

Bytes

Boolean