本文介紹在Java SDK中如何通過SQL查詢表中的資料。
注意事項
Table StoreJava SDK從5.13.0版本開始支援SQL查詢功能,使用SQL查詢功能時,請確保安裝了正確的Java SDK版本。
前提條件
方法說明
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"));
}
}