Your first query with PlatformIO¶
In this tutorial you'll build a PlatformIO project for an ESP32 that joins your Wi-Fi network, logs in to SQL Server and prints rows from a table. On the way, you'll see how SQL Server tells you about a mistake in a query.
You need:
- An ESP32 development board (any ESP32 DevKit will do) and a USB cable
- PlatformIO: the VS Code extension, or PlatformIO Core on the command line
- A 2.4 GHz Wi-Fi network that your computer is on too
- A SQL Server: see Before you start
1. Create the project¶
Create an empty folder called first-query, with a platformio.ini file in
it:
[env:esp32dev]
platform = espressif32
board = esp32dev
framework = arduino
monitor_speed = 115200
lib_deps =
mustafakemalgilor/tdslite
lib_deps tells PlatformIO to download tdslite from its registry the first
time you build.
Create a src folder next to it, and a src/main.cpp file. You'll fill it in
the next steps.
2. Set up the driver¶
Start main.cpp with the headers:
Add your Wi-Fi network's name and password, and your computer's IP address:
// Your Wi-Fi network
static const char * wifi_ssid = "<your Wi-Fi name>";
static const char * wifi_password = "<your Wi-Fi password>";
// The computer that runs SQL Server
static const char db_server [] = "192.168.1.10";
Create the network buffer and the driver. On Arduino-style boards, the driver
works with the board's own network client; here it's WiFiClient:
// The buffer that tdslite uses to send and receive data
static tdsl::uint8_t net_buf [4096] = {};
// The driver, talking over Wi-Fi
static tdsl::arduino_driver<WiFiClient> driver{net_buf};
3. Add the callbacks¶
SQL Server sends messages along with its answers: a note that the database changed, or the reason a query failed. tdslite passes each one to an info callback:
// Called for each message that SQL Server sends, errors included
static void print_message(void *, const tdsl::tds_info_token & token) noexcept {
Serial.print(token.is_error() ? "server error: " : "server info: ");
// The message text is UTF-16; this prints its ASCII characters
for (const char16_t c : token.msgtext) {
Serial.print(static_cast<char>(c));
}
Serial.println();
}
And it passes each row of a result set to a row callback:
// Called once for each row of a result set
static void print_row(void *, const tdsl::tds_colmetadata_token &, const tdsl::tdsl_row & row) {
const auto id = row [0].as<tdsl::int32_t>();
const auto name = row [1].as<tdsl::char_view>();
Serial.printf("%d: %.*s\n", static_cast<int>(id), static_cast<int>(name.size()), name.data());
}
4. Connect¶
Write setup(). Join the Wi-Fi network first:
void setup() {
Serial.begin(115200);
WiFi.mode(WIFI_STA);
WiFi.begin(wifi_ssid, wifi_password);
Serial.print("Connecting to Wi-Fi");
while (WiFi.status() != WL_CONNECTED) {
Serial.print('.');
delay(500);
}
Serial.print(" connected, IP address ");
Serial.println(WiFi.localIP());
Then register the info callback and log in:
driver.set_info_callback(print_message);
decltype(driver)::connection_parameters params;
params.server_name = db_server;
params.port = 1433;
params.user_name = "sa";
params.password = "Tutorial-Passw0rd";
const auto cr = driver.connect(params);
if (not(cr == decltype(driver)::e_driver_error_code::success)) {
Serial.printf("Could not connect to SQL Server (error %d)\n", static_cast<int>(cr));
return;
}
Serial.println("Connected to SQL Server");
5. Run queries¶
Create a table, fill it, and read it back:
driver.execute_query("CREATE TABLE #fruits(id INT, name VARCHAR(16))");
driver.execute_query("INSERT INTO #fruits VALUES (1, 'apple'), (2, 'banana'), (3, 'cherry')");
const auto result = driver.execute_query("SELECT id, name FROM #fruits", print_row);
Serial.printf("%u row(s)\n", static_cast<unsigned>(result.affected_rows));
Now make a mistake on purpose: select from a table that doesn't exist.
// This table doesn't exist: SQL Server answers with an error message
const auto bad = driver.execute_query("SELECT * FROM #vegetables");
if (not bad) {
Serial.println("The query failed, see the server error above");
}
}
void loop() {
delay(1000);
}
6. Build, upload and watch¶
Plug in the board, then run:
In VS Code, click PlatformIO: Upload and then PlatformIO: Serial Monitor in the status bar instead.
You'll see something like:
Connecting to Wi-Fi..... connected, IP address 192.168.1.42
server info: Changed database context to 'master'.
server info: Changed language setting to us_english.
Connected to SQL Server
1: apple
2: banana
3: cherry
3 row(s)
server error: Invalid object name '#vegetables'.
The query failed, see the server error above
The server info lines are SQL Server confirming the login. The server
error line is its answer to the bad query: the result of execute_query
told you that the query failed, and the info callback told you why.
What you've done¶
You've built a PlatformIO project that pulls tdslite from the registry, connected an ESP32 to SQL Server over Wi-Fi, read rows, and seen how a failed query reports its error.
The complete program
#include <Arduino.h>
#include <WiFi.h>
#include <tdslite.h>
// Your Wi-Fi network
static const char * wifi_ssid = "<your Wi-Fi name>";
static const char * wifi_password = "<your Wi-Fi password>";
// The computer that runs SQL Server
static const char db_server [] = "192.168.1.10";
// The buffer that tdslite uses to send and receive data
static tdsl::uint8_t net_buf [4096] = {};
// The driver, talking over Wi-Fi
static tdsl::arduino_driver<WiFiClient> driver{net_buf};
// Called for each message that SQL Server sends, errors included
static void print_message(void *, const tdsl::tds_info_token & token) noexcept {
Serial.print(token.is_error() ? "server error: " : "server info: ");
// The message text is UTF-16; this prints its ASCII characters
for (const char16_t c : token.msgtext) {
Serial.print(static_cast<char>(c));
}
Serial.println();
}
// Called once for each row of a result set
static void print_row(void *, const tdsl::tds_colmetadata_token &, const tdsl::tdsl_row & row) {
const auto id = row [0].as<tdsl::int32_t>();
const auto name = row [1].as<tdsl::char_view>();
Serial.printf("%d: %.*s\n", static_cast<int>(id), static_cast<int>(name.size()), name.data());
}
void setup() {
Serial.begin(115200);
WiFi.mode(WIFI_STA);
WiFi.begin(wifi_ssid, wifi_password);
Serial.print("Connecting to Wi-Fi");
while (WiFi.status() != WL_CONNECTED) {
Serial.print('.');
delay(500);
}
Serial.print(" connected, IP address ");
Serial.println(WiFi.localIP());
driver.set_info_callback(print_message);
decltype(driver)::connection_parameters params;
params.server_name = db_server;
params.port = 1433;
params.user_name = "sa";
params.password = "Tutorial-Passw0rd";
const auto cr = driver.connect(params);
if (not(cr == decltype(driver)::e_driver_error_code::success)) {
Serial.printf("Could not connect to SQL Server (error %d)\n", static_cast<int>(cr));
return;
}
Serial.println("Connected to SQL Server");
driver.execute_query("CREATE TABLE #fruits(id INT, name VARCHAR(16))");
driver.execute_query("INSERT INTO #fruits VALUES (1, 'apple'), (2, 'banana'), (3, 'cherry')");
const auto result = driver.execute_query("SELECT id, name FROM #fruits", print_row);
Serial.printf("%u row(s)\n", static_cast<unsigned>(result.affected_rows));
// This table doesn't exist: SQL Server answers with an error message
const auto bad = driver.execute_query("SELECT * FROM #vegetables");
if (not bad) {
Serial.println("The query failed, see the server error above");
}
}
void loop() {
delay(1000);
}
Next steps¶
- Run parameterized queries to put sensor readings into a table safely.
- Connect with TLS to encrypt the connection with
WiFiClientSecure. - Handle errors and server messages for all the ways a query can fail.