使用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
文檔內容是否對您有幫助?