本文介绍在Java SDK中如何通过SQL查询表中的数据。
注意事项
表格存储Java SDK从5.13.0版本开始支持SQL查询功能,使用SQL查询功能时,请确保安装了正确的Java SDK版本。
通过SQL查询数据前,您需要为数据表或多元索引创建映射表。
前提条件
方法说明
public SQLQueryResponse sqlQuery(SQLQueryRequest request) throws TableStoreException, ClientException
示例代码
以下示例通过 SELECT
语句查询 test_table 表中的数据且最多返回10行数据。
运行代码前,请根据您的表信息替换代码中的表名称和字段名称。
public static void queryDataExample(SyncClient client) {
// 查询 SQL
SQLQueryRequest request = new SQLQueryRequest("select order_id, user_id, sku_id, price, num, total_price, order_status, create_time, modified_time from test_table limit 10;");
SQLQueryResponse response = client.sqlQuery(request);
// RequestId 信息
System.out.println("RequestId: " + response.getRequestId());
/*// 读吞吐量消耗信息
System.out.println("读吞吐量消耗(按表统计):");
for(Map.Entry<String, ConsumedCapacity> entry : response.getConsumedCapacity().entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue().getCapacityUnit().getReadCapacityUnit() + "CU");
}*/
// 获取 SQL 查询结果
SQLResultSet resultSet = response.getSQLResultSet();
// 返回 Schema 信息
System.out.println("Schema: " + response.getSQLResultSet().getSQLTableMeta().getSchema());
// 数据明细
System.out.println("数据明细:");
while (resultSet.hasNext()) {
SQLRow row = resultSet.next();
System.out.println(row.get("order_id") + ", "
+ row.get("user_id") + ", "
+ row.get("sku_id") + ", "
+ row.get("price") + ", "
+ row.get("num") + ", "
+ row.get("total_price") + ", "
+ row.get("order_status") + ", "
+ row.get("create_time") + ", "
+ row.get("modified_time"));
}
}
常见问题
相关文档
该文章对您有帮助吗?