Use the Tablestore SDK for Go to query data by running SQL statements.
Prerequisites
A client is initialized. For more information, see Initialize a Tablestore client.
A mapping table is created for the table you want to query. For more information, see Create a mapping table.
Parameters
|
Parameter |
Description |
|
query |
The SQL statement to execute. |
Examples
The following example runs a SELECT statement against test_table and returns up to 20 rows. The response includes the statement type, the result set schema, and the row data.
func queryData(client *tablestore.TableStoreClient) {
// Build the SQL request.
request := &tablestore.SQLQueryRequest{Query: "select pk, long_value, double_value, string_value, bool_value from test_table limit 20"}
// Execute the SQL request.
response, err := client.SQLQuery(request)
if err != nil {
panic(err)
}
// Print the statement type.
fmt.Printf("response type: %v\n", response.StmtType.String())
// Print the result set schema.
columns := response.ResultSet.Columns()
fmt.Printf("response table meta: [")
for i := 0; i < len(columns); i++ {
fmt.Printf("%v:%v ", columns[i].Name, columns[i].Type.String())
}
// Iterate over the result set rows.
resultSet := response.ResultSet
fmt.Println("]\nresponse resultset:")
for resultSet.HasNext() {
row := resultSet.Next()
stringValue, _ := row.GetString(0)
fmt.Printf("%v, ", stringValue)
stringValue, _ = row.GetStringByName("pk")
fmt.Printf("%v, ", stringValue)
longValue, _ := row.GetFloat64(1)
fmt.Printf("%v, ", longValue)
longValue, _ = row.GetFloat64ByName("long_value")
fmt.Printf("%v, ", longValue)
floatValue, _ := row.GetFloat64(2)
fmt.Printf("%v, ", floatValue)
floatValue, _ = row.GetFloat64ByName("double_value")
fmt.Printf("%v, ", floatValue)
stringValue, _ = row.GetString(3)
fmt.Printf("%v, ", stringValue)
stringValue, _ = row.GetStringByName("string_value")
fmt.Printf("%v, ", stringValue)
boolValue, _ := row.GetBool(4)
fmt.Printf("%v, ", boolValue)
boolValue, _ = row.GetBoolByName("bool_value")
fmt.Printf("%v\n", boolValue)
}
}
Sample response:
response type: SQL_SELECT
response table meta: [pk:STRING long_value:INTEGER double_value:DOUBLE string_value:STRING bool_value:BOOLEAN]
response resultset:
binary_null, binary_null, 0, 0, 1, 1, a, a, false, false
bool_null, bool_null, 0, 0, 1, 1, a, a, false, false
double_null, double_null, 0, 0, 1, 1, a, a, false, false
long_null, long_null, 0, 0, 1, 1, a, a, false, false
string_null, string_null, 0, 0, 1, 1, , , false, false