使用SQL語句查詢到時間類型(包括Datetime、Date和Time)資料後,您可以需要根據實際擷取具體資料。
前提條件
介面說明
擷取不同時間類型的介面說明請參見下表,請根據實際時間類型選擇。
重要
getDateTime
擷取的時間時區預設為UTC時區,請根據需要進行時區轉換。
時間類型 | 介面 | 參數 | 傳回型別 |
Datetime | getDateTime | columnIndex:int | time.Time |
Datetime | getDateTime | columnName:string | time.Time |
Time | getTime | columnIndex:int | time.Duration |
Time | getTime | columnName:string | time.Duration |
Date | getDate | columnIndex:int | time.Time |
Date | getDate | columnName:string | time.Time |
參數
參數 | 說明 |
query | SQL語句,請根據所需功能進行設定。 |
樣本
使用select from_unixtime(time_col) as datetime_value,time(from_unixtime(time_col)) as time_value, date(from_unixtime(time_col)) as date_value from test_table limit 1
語句查詢test_table表中time_col列資料並將其轉換為Datetime、Time、Date三種類型,最多返回1行資料。系統會返回查詢語句的請求類型、傳回值Schema、返回結果等資訊。
func queryData(client *tablestore.TableStoreClient) {
// 建立SQL請求。
request := &tablestore.SQLQueryRequest{Query: "select from_unixtime(time_col) as datetime_value,time(from_unixtime(time_col)) as time_value, date(from_unixtime(time_col)) as date_value from test_table limit 1"}
// 擷取SQL的響應結果。
response, err := client.SQLQuery(request)
if err != nil {
panic(err)
}
// 擷取SQL的返回結果。
resultSet := response.ResultSet
fmt.Println("response resultset:")
for resultSet.HasNext() {
row := resultSet.Next()
for i := 0; i < len(columns); i++ {
name := columns[i].Name
isnull, err := row.IsNull(i)
if err != nil {
println("[INFO:] get column error, name: ", name, ", error: ", err.Error())
continue
}
if isnull {
println("[INFO]: column is SQL NULL, name: ", name)
continue
}
switch columns[i].Type {
case tablestore.ColumnType_DATETIME:
time, err := row.GetDateTime(i)
if err != nil {
println("[INFO:] get column error, name: ", name, ", error: ", err.Error())
}
println(time.Local().String())
time, err = row.GetDateTimeByName("datetime_value")
if err != nil {
println("[INFO:] get column error, name: ", name, ", error: ", err.Error())
}
println(time.String())
case tablestore.ColumnType_TIME:
duration, err := row.GetTime(i)
if err != nil {
println("[INFO:] get column error, name: ", name, ", error: ", err.Error())
}
println(duration.String())
duration, err = row.GetTimeByName("time_value")
if err != nil {
println("[INFO:] get column error, name: ", name, ", error: ", err.Error())
}
println(duration.String())
case tablestore.ColumnType_DATE:
date, err := row.GetDate(i)
if err != nil {
println("[INFO:] get column error, name: ", name, ", error: ", err.Error())
}
println(date.String())
date, err = row.GetDateByName("date_value")
if err != nil {
println("[INFO:] get column error, name: ", name, ", error: ", err.Error())
}
println(date.String())
}
}
}
}
返回結果如下所示。
response resultset:
2023-11-09 10:14:00.01 +0800 CST
2023-11-09 10:14:00.01 +0800 CST
10h14m0.01s
10h14m0.01s
2023-11-09 00:00:00 +0000 UTC
2023-11-09 00:00:00 +0000 UTC