Skip to content

Instantly share code, notes, and snippets.

@patrick-palka
Created August 6, 2019 20:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save patrick-palka/ffd836d0294f71d183f4199d0e842186 to your computer and use it in GitHub Desktop.
Save patrick-palka/ffd836d0294f71d183f4199d0e842186 to your computer and use it in GitHub Desktop.
SQLite wrapper example
#include "SQLiteWrapper.h"
int main(void) {
static const char db_name[] = "example.db";
using db = sqlite::Database<db_name>;
static const char create_table_query[]
= R"(create table if not exists users (first_name text,
last_name text,
age integer,
website text))";
db::query<create_table_query>();
static const char clear_table_query[] = R"(delete from users)";
db::query<clear_table_query>();
static const char insert_users_query[]
= R"(insert into users values (?1, ?2, ?3, ?4))";
db::query<insert_users_query>("John", "Doe", 29, "google.com");
db::query<insert_users_query>("Mary", "Smith", 28, std::nullopt);
db::query<insert_users_query>("James", "Smith", 20, "yahoo.com");
static const char select_users_query[]
= R"(select first_name, last_name, age, website
from users where age = ?1 or substr(first_name, 1, 1) = ?2)";
auto fetch_row = db::query<select_users_query>(29, "M");
std::string_view first_name, last_name;
int age;
std::optional<std::string_view> website;
while (fetch_row(first_name, last_name, age, website)) {
std::cout << first_name << " "
<< last_name << ", "
<< age << ", "
<< (website ? *website : "<no website>")
<< std::endl;
}
}
@patrick-palka
Copy link
Author

Output:

John Doe, 29, google.com
Mary Smith, 28, <no website>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment