Your first query on desktop¶
In this tutorial you'll write a small command line program that logs in to SQL Server, creates a table and prints its rows. You need no hardware, and because tdslite is header-only, nothing to build or install except your own program.
You need:
- Linux or macOS, with
gitand a C++11 compiler (g++orclang++) - A SQL Server: see Before you start. Running it in Docker on the same computer is the easiest.
Windows
The backend this tutorial uses is written against BSD sockets, which Windows doesn't provide. On Windows, follow the tutorial inside WSL.
1. Get tdslite¶
Make a folder for the tutorial and clone tdslite into it:
That's all the setup: the program only needs tdslite/src on its include
path.
2. Write the program¶
Create first_query.cpp next to the tdslite folder. Start with the header
of the BSD sockets backend, which brings in the rest of tdslite:
tdslite sends and receives through a buffer that you give it:
SQL Server sends messages along with its answers, such as the reason a login 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 {
std::printf("server %s %u: ", token.is_error() ? "error" : "info",
static_cast<unsigned>(token.number));
// The message text is UTF-16; this prints its ASCII characters
for (const char16_t c : token.msgtext) {
std::putchar(static_cast<char>(c));
}
std::putchar('\n');
}
and 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>();
std::printf("%d: %.*s\n", static_cast<int>(id), static_cast<int>(name.size()), name.data());
}
In main, create the driver, register the info callback and log in:
int main() {
tdsl::socket_driver driver{net_buf};
driver.set_info_callback(print_message);
tdsl::socket_driver::connection_parameters params;
params.server_name = "127.0.0.1";
params.port = 1433;
params.user_name = "sa";
params.password = "Tutorial-Passw0rd";
params.conn_retry_count = 1;
const auto cr = driver.connect(params);
if (not(cr == tdsl::socket_driver::e_driver_error_code::success)) {
std::printf("could not connect to SQL Server (error %d)\n", static_cast<int>(cr));
return 1;
}
std::printf("connected\n");
Then 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);
if (not result) {
std::printf("the query failed\n");
return 1;
}
std::printf("%u row(s)\n", static_cast<unsigned>(result.affected_rows));
return 0;
}
3. Build and run¶
You'll see:
server info 5701: Changed database context to 'master'.
server info 5703: Changed language setting to us_english.
connected
1: apple
2: banana
3: cherry
3 row(s)
The first two lines are SQL Server confirming the login, through your info callback.
4. See a failed login¶
Change the password in first_query.cpp to something wrong, build and run
again:
connect returned login_failed (2), and the info callback received SQL
Server's explanation. Put the right password back.
What you've done¶
You've built a program with tdslite straight from its source folder, logged in to SQL Server, read rows, and seen how tdslite reports a failed login.
The complete program
#include <tdslite-net/socket/tdsl_netimpl_socket.hpp>
#include <cstdio>
// The buffer that tdslite uses to send and receive data
static tdsl::uint8_t net_buf [8192] = {};
// Called for each message that SQL Server sends, errors included
static void print_message(void *, const tdsl::tds_info_token & token) noexcept {
std::printf("server %s %u: ", token.is_error() ? "error" : "info",
static_cast<unsigned>(token.number));
// The message text is UTF-16; this prints its ASCII characters
for (const char16_t c : token.msgtext) {
std::putchar(static_cast<char>(c));
}
std::putchar('\n');
}
// 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>();
std::printf("%d: %.*s\n", static_cast<int>(id), static_cast<int>(name.size()), name.data());
}
int main() {
tdsl::socket_driver driver{net_buf};
driver.set_info_callback(print_message);
tdsl::socket_driver::connection_parameters params;
params.server_name = "127.0.0.1";
params.port = 1433;
params.user_name = "sa";
params.password = "Tutorial-Passw0rd";
params.conn_retry_count = 1;
const auto cr = driver.connect(params);
if (not(cr == tdsl::socket_driver::e_driver_error_code::success)) {
std::printf("could not connect to SQL Server (error %d)\n", static_cast<int>(cr));
return 1;
}
std::printf("connected\n");
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);
if (not result) {
std::printf("the query failed\n");
return 1;
}
std::printf("%u row(s)\n", static_cast<unsigned>(result.affected_rows));
return 0;
}
Next steps¶
- Run parameterized queries.
- Connect with TLS using the Boost.ASIO backend.
- Handle errors and server messages.
- Results and error codes lists every value
connectand the queries can return.