Skip to content

Your first query on ESP-IDF

In this tutorial you'll build an ESP-IDF application that connects to your network, logs in to SQL Server, and logs the rows of a table. You'll set the connection details in menuconfig, the way ESP-IDF projects usually do.

You need:

  • An ESP32, ESP32-C3 or ESP32-S3 board and a USB cable
  • ESP-IDF 5.0 or newer, installed and set up in your shell (idf.py --version works)
  • A Wi-Fi network that your computer is on too
  • A SQL Server: see Before you start

1. Create the project

Create a project and choose your chip:

idf.py create-project first-query
cd first-query
idf.py set-target esp32   # or esp32c3, esp32s3

tdslite is C++, so rename the generated source file:

mv main/first-query.c main/main.cpp

and replace main/CMakeLists.txt with:

idf_component_register(SRCS "main.cpp"
                       INCLUDE_DIRS "."
                       PRIV_REQUIRES nvs_flash esp_netif esp_event)

2. Add the dependencies

Add tdslite from the ESP Component Registry:

idf.py add-dependency "tdslite/tdslite"

This creates main/idf_component.yml. The program also uses the Wi-Fi helper that comes with ESP-IDF's examples. Add it to the dependencies in main/idf_component.yml:

dependencies:
  tdslite/tdslite: "*"
  protocol_examples_common:
    path: ${IDF_PATH}/examples/common_components/protocol_examples_common

tdslite reports errors through return values, so exceptions and RTTI can stay off. Create sdkconfig.defaults in the project folder:

# Wi-Fi is the default connection type of protocol_examples_common.
# Set the SSID/password in menuconfig -> Example Connection Configuration,
# and the server details in menuconfig -> tdslite example.

# tdslite reports errors with return values; no exceptions or RTTI needed.
CONFIG_COMPILER_CXX_EXCEPTIONS=n
CONFIG_COMPILER_CXX_RTTI=n

3. Add the settings

Create main/Kconfig.projbuild. It adds a tdslite example menu to menuconfig, where you'll enter the server's details:

menu "tdslite example"

    config TDSLITE_EXAMPLE_SERVER
        string "SQL Server host name or IP address"
        default "192.168.1.100"

    config TDSLITE_EXAMPLE_PORT
        int "SQL Server port"
        range 1 65535
        default 1433

    config TDSLITE_EXAMPLE_USER
        string "User name (SQL Server authentication)"
        default "sa"

    config TDSLITE_EXAMPLE_PASSWORD
        string "Password"
        default ""

    config TDSLITE_EXAMPLE_DATABASE
        string "Database"
        default "master"

endmenu

4. Write the program

Open main/main.cpp and replace its contents. Start with the headers. The driver comes from the BSD sockets backend, which works on top of ESP-IDF's lwIP:

#include <tdslite-net/socket/tdsl_netimpl_socket.hpp>

#include <esp_event.h>
#include <esp_log.h>
#include <esp_netif.h>
#include <esp_system.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <nvs_flash.h>
#include <protocol_examples_common.h>

#include <cstdio>

static const char * TAG = "tdslite-example";

Create the network buffer and the driver, outside any function:

// The network buffer. Each row of a result set must fit into it.
// Kept off the stack: the main task's stack is small.
static tdsl::uint8_t net_buf [4096] = {};
static tdsl::socket_driver driver{net_buf};

Add a callback for the messages SQL Server sends, and one for the rows of a result set:

// Print INFO and ERROR messages that the server sends (e.g. "Changed database
// context to 'master'", or the reason of a failed login)
static void info_callback(void *, const tdsl::tds_info_token & token) noexcept {
    char msg [128];
    size_t n = 0;
    for (const auto ch : token.msgtext) {
        if (n == sizeof(msg) - 1) {
            break;
        }
        msg [n++] = static_cast<char>(ch); // ASCII is enough for an example
    }
    msg [n] = '\0';
    ESP_LOGI(TAG, "server %s: %s", token.is_info() ? "info" : "error", msg);
}

// Called 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>();
    ESP_LOGI(TAG, "  row: id=%ld name=%.*s", static_cast<long>(id), static_cast<int>(name.size()),
             name.data());
}

Now app_main. Bring up the network first:

extern "C" void app_main(void) {
    ESP_ERROR_CHECK(nvs_flash_init());
    ESP_ERROR_CHECK(esp_netif_init());
    ESP_ERROR_CHECK(esp_event_loop_create_default());
    ESP_ERROR_CHECK(example_connect());

Log in with the settings from menuconfig:

    driver.set_info_callback(&info_callback, nullptr);

    tdsl::socket_driver::connection_parameters params;
    params.server_name = CONFIG_TDSLITE_EXAMPLE_SERVER;
    params.port        = CONFIG_TDSLITE_EXAMPLE_PORT;
    params.user_name   = CONFIG_TDSLITE_EXAMPLE_USER;
    params.password    = CONFIG_TDSLITE_EXAMPLE_PASSWORD;
    params.db_name     = CONFIG_TDSLITE_EXAMPLE_DATABASE;
    params.app_name    = "tdslite esp-idf example";

    ESP_LOGI(TAG, "connecting to %s:%d", CONFIG_TDSLITE_EXAMPLE_SERVER,
             CONFIG_TDSLITE_EXAMPLE_PORT);
    const auto cr = driver.connect(params);
    if (not(cr == tdsl::socket_driver::e_driver_error_code::success)) {
        ESP_LOGE(TAG, "connect failed (%d)", static_cast<int>(cr));
        return;
    }
    ESP_LOGI(TAG, "logged in");

Then create a table, fill it, and read it back:

    // `#` makes it a temporary table that's dropped when the session ends
    const auto ct =
        driver.execute_query("CREATE TABLE #example(id INT NOT NULL, name VARCHAR(32) NOT NULL);");
    if (not ct) {
        ESP_LOGE(TAG, "CREATE TABLE failed");
        return;
    }

    const auto ir =
        driver.execute_query("INSERT INTO #example VALUES (1, 'apple'), (2, 'banana'), (3, 'cherry');");
    if (not ir) {
        ESP_LOGE(TAG, "INSERT failed");
        return;
    }
    ESP_LOGI(TAG, "inserted %lu row(s)", static_cast<unsigned long>(ir.affected_rows));

    const auto sr = driver.execute_query("SELECT id, name FROM #example ORDER BY id;", &print_row);
    if (not sr) {
        ESP_LOGE(TAG, "SELECT failed");
        return;
    }
    ESP_LOGI(TAG, "selected %lu row(s)", static_cast<unsigned long>(sr.affected_rows));
}

5. Configure, build and run

Open the configuration menu:

idf.py menuconfig
  • In Example Connection Configuration, enter your Wi-Fi network's name and password.
  • In tdslite example, enter your computer's IP address as the host name, and Tutorial-Passw0rd as the password.

Save with S and quit with Q. Then build, flash and watch the log:

idf.py flash monitor

After the Wi-Fi connection, you'll see something like this (the timestamps will differ):

I (3021) tdslite-example: connecting to 192.168.1.10:1433
I (3215) tdslite-example: server info: Changed database context to 'master'.
I (3216) tdslite-example: server info: Changed language setting to us_english.
I (3218) tdslite-example: logged in
I (3260) tdslite-example: inserted 3 row(s)
I (3281) tdslite-example:   row: id=1 name=apple
I (3282) tdslite-example:   row: id=2 name=banana
I (3283) tdslite-example:   row: id=3 name=cherry
I (3284) tdslite-example: selected 3 row(s)

Quit the monitor with Ctrl+].

What you've done

You've built an ESP-IDF application with tdslite from the component registry, configured it through menuconfig, and run queries on SQL Server from an ESP32.

The complete program

This is examples/esp-idf/query in the tdslite repository, which also prints the free heap and stack at the end.

/**
 * ____________________________________________________
 * tdslite ESP-IDF example
 *
 * Connects to a network (Wi-Fi or Ethernet, see menuconfig ->
 * "Example Connection Configuration"), logs in to SQL Server
 * (menuconfig -> "tdslite example") and runs a few queries.
 *
 * The --8<-- lines mark the parts that the ESP-IDF tutorial
 * shows (docs/tutorials/esp-idf.md).
 *
 * SPDX-License-Identifier:    MIT
 * ____________________________________________________
 */

#include <tdslite-net/socket/tdsl_netimpl_socket.hpp>

#include <esp_event.h>
#include <esp_log.h>
#include <esp_netif.h>
#include <esp_system.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <nvs_flash.h>
#include <protocol_examples_common.h>

#include <cstdio>

static const char * TAG = "tdslite-example";

// The network buffer. Each row of a result set must fit into it.
// Kept off the stack: the main task's stack is small.
static tdsl::uint8_t net_buf [4096] = {};
static tdsl::socket_driver driver{net_buf};

// Print INFO and ERROR messages that the server sends (e.g. "Changed database
// context to 'master'", or the reason of a failed login)
static void info_callback(void *, const tdsl::tds_info_token & token) noexcept {
    char msg [128];
    size_t n = 0;
    for (const auto ch : token.msgtext) {
        if (n == sizeof(msg) - 1) {
            break;
        }
        msg [n++] = static_cast<char>(ch); // ASCII is enough for an example
    }
    msg [n] = '\0';
    ESP_LOGI(TAG, "server %s: %s", token.is_info() ? "info" : "error", msg);
}

// Called 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>();
    ESP_LOGI(TAG, "  row: id=%ld name=%.*s", static_cast<long>(id), static_cast<int>(name.size()),
             name.data());
}

extern "C" void app_main(void) {
    ESP_ERROR_CHECK(nvs_flash_init());
    ESP_ERROR_CHECK(esp_netif_init());
    ESP_ERROR_CHECK(esp_event_loop_create_default());
    ESP_ERROR_CHECK(example_connect());

    driver.set_info_callback(&info_callback, nullptr);

    tdsl::socket_driver::connection_parameters params;
    params.server_name = CONFIG_TDSLITE_EXAMPLE_SERVER;
    params.port        = CONFIG_TDSLITE_EXAMPLE_PORT;
    params.user_name   = CONFIG_TDSLITE_EXAMPLE_USER;
    params.password    = CONFIG_TDSLITE_EXAMPLE_PASSWORD;
    params.db_name     = CONFIG_TDSLITE_EXAMPLE_DATABASE;
    params.app_name    = "tdslite esp-idf example";

    ESP_LOGI(TAG, "connecting to %s:%d", CONFIG_TDSLITE_EXAMPLE_SERVER,
             CONFIG_TDSLITE_EXAMPLE_PORT);
    const auto cr = driver.connect(params);
    if (not(cr == tdsl::socket_driver::e_driver_error_code::success)) {
        ESP_LOGE(TAG, "connect failed (%d)", static_cast<int>(cr));
        return;
    }
    ESP_LOGI(TAG, "logged in");

    // `#` makes it a temporary table that's dropped when the session ends
    const auto ct =
        driver.execute_query("CREATE TABLE #example(id INT NOT NULL, name VARCHAR(32) NOT NULL);");
    if (not ct) {
        ESP_LOGE(TAG, "CREATE TABLE failed");
        return;
    }

    const auto ir =
        driver.execute_query("INSERT INTO #example VALUES (1, 'apple'), (2, 'banana'), (3, 'cherry');");
    if (not ir) {
        ESP_LOGE(TAG, "INSERT failed");
        return;
    }
    ESP_LOGI(TAG, "inserted %lu row(s)", static_cast<unsigned long>(ir.affected_rows));

    const auto sr = driver.execute_query("SELECT id, name FROM #example ORDER BY id;", &print_row);
    if (not sr) {
        ESP_LOGE(TAG, "SELECT failed");
        return;
    }
    ESP_LOGI(TAG, "selected %lu row(s)", static_cast<unsigned long>(sr.affected_rows));

    ESP_LOGI(TAG, "done. free heap: %lu bytes, main task stack high water mark: %lu bytes",
             static_cast<unsigned long>(esp_get_free_heap_size()),
             static_cast<unsigned long>(uxTaskGetStackHighWaterMark(nullptr)));
}

Next steps