Run parameterized queries¶
Use execute_rpc when a query contains values that come from outside the
program: sensor readings, user input, anything you'd otherwise paste into the
SQL text. The values travel separately from the query, so they can't change
what the query does, and you don't have to quote or escape them.
Bind the parameters¶
- Create one
tdsl::sql_parameter_*object per value, of the type of the column it goes into. - Put them in a
tdsl::sql_parameter_bindingarray. The first is@p0in the query, the second@p1, and so on. - Pass the query and the array to
execute_rpc.
tdsl::sql_parameter_varchar name{"apple"};
tdsl::sql_parameter_int stock{12};
tdsl::sql_parameter_binding params []{name, stock};
auto result = driver.execute_rpc(
TDSL_PMEMSTR("INSERT INTO fruits(name, stock) VALUES (@p0, @p1)"), params);
execute_rpc doesn't take a plain string literal. Wrap the query in
TDSL_PMEMSTR(...) to keep it in flash (on AVR boards this saves RAM), or in
tdsl::string_view{...}.
Read rows with parameters¶
Pass a row callback as the fourth argument, after the mode:
tdsl::sql_parameter_int min_stock{10};
tdsl::sql_parameter_binding params []{min_stock};
auto result = driver.execute_rpc(
TDSL_PMEMSTR("SELECT name, stock FROM fruits WHERE stock >= @p0"), params,
tdsl::rpc_mode::executesql, print_row);
Check the result¶
The result of execute_rpc converts to true on success. Then get() is the
number of rows the query affected or returned; otherwise error() tells why it
failed:
if (result) {
Serial.println(result.get());
} else if (result.error() == tdsl::detail::e_rpc_error_code::server_error) {
// SQL Server rejected the query; the info callback received its message
}
All the error codes are listed in Results and error codes.
Pass strings and bytes¶
String and byte parameters hold a view of your data, not a copy. Keep the data
alive until execute_rpc returns.
// varchar, char: 8-bit characters
tdsl::sql_parameter_varchar a{"hello"};
// nvarchar, nchar: UTF-16
tdsl::sql_parameter_nvarchar b{tdsl::wstring_view{u"héllo"}};
// varbinary, binary, uniqueidentifier: raw bytes
const tdsl::uint8_t payload [] = {0xDE, 0xAD, 0xBE, 0xEF};
tdsl::sql_parameter_varbinary c{tdsl::byte_view{payload}};
Reuse parameters in a loop¶
Parameters can be assigned a new value. A binding records where each parameter's data is and, for strings and bytes, how long it is, so build the binding array after the assignment:
tdsl::sql_parameter_int reading{};
void loop() {
reading = analogRead(A0);
tdsl::sql_parameter_binding params []{reading};
driver.execute_rpc(TDSL_PMEMSTR("INSERT INTO readings VALUES (@p0)"), params);
delay(1000);
}
Related¶
- Data types: which parameter type goes with which SQL type, and which types can't be bound yet.
- Limits: the length limit of a query.
- Example sketch: 05 - Execute query with parameters