This topic describes how to use Tablestore SDK for Go to query data by executing SQL statements.
Prerequisites
A client is initialized. For more information, see Initialize a Tablestore client.
A mapping table is created for the table in which you want to query data. For more information, see Create a mapping table.
Parameters
Parameter | Description |
query | The SQL statement. Configure this parameter based on the required feature. |
Examples
The following example shows how to use the select pk, long_value, double_value, string_value, bool_value from test_table limit 20 statement to query data in the test_table table and return a maximum of 20 rows of data. The system returns the request type of the query statement, the schema of the return value, and the returned results.
func queryData(client *tablestore.TableStoreClient) {
// Create a SQL request.
request := &tablestore.SQLQueryRequest{Query: "select pk, long_value, double_value, string_value, bool_value from test_table limit 20"}
// Obtain the response to the SQL request.
response, err := client.SQLQuery(request)
if err != nil {
panic(err)
}
// Obtain the SQL request type.
fmt.Printf("response type: %v\n", response.StmtType.String())
// Obtain the schema of the return value of the SQL request.
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())
}
// Obtain the returned results of the SQL request.
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