nlib
oss/readsqldb/readsqldb.cpp

SQLite3をC/C++から利用するサンプルです。既存のデータベースを読み込んで処理を行います。

#ifndef DBDIR
# error
#endif
#define STRING_(str) #str
#define STRING(str) STRING_(str)
#include "nn/nlib/Config.h"
#include "sqlite3.h"
static int callback(void* arg, int columns, char** value, char** name) {
NLIB_UNUSED(arg);
for (int i = 0; i < columns; ++i) {
nlib_printf("[%s=%s] ", name[i], value[i]);
}
nlib_printf("\n");
return 0;
}
bool SampleMain(int, char**) {
const char* dbdir = STRING(DBDIR);
nlib_printf("DBDIR is '%s'\n", dbdir);
sqlite3_nlib_set_directory(SQLITE_NLIB_DATA_DIRECTORY_TYPE, dbdir);
sqlite3_nlib_set_directory(SQLITE_NLIB_TEMP_DIRECTORY_TYPE, dbdir);
sqlite3* db;
// Reads the database from file.
// sample.db is the same as the one that sqlfromc.cpp sample generates.
int result;
result = sqlite3_open("sample.db", &db); // Reads ${DBDIR}/sample.db
if (result != SQLITE_OK) return false;
// Prints all the menus.
char* errmsg = NULL;
nlib_printf("> SELECT * FROM t_menu;\n");
result = sqlite3_exec(db,
"SELECT * FROM t_menu",
callback,
NULL,
&errmsg);
nlib_printf("\n");
if (result != SQLITE_OK) {
nlib_printf("%s\n", errmsg);
sqlite3_free(errmsg);
sqlite3_close(db);
return false;
}
// Prints all the menus beginning with 't'.
nlib_printf("> SELECT * FROM t_menu WHERE LIKE 't%%';\n");
result = sqlite3_exec(db,
"SELECT * FROM t_menu WHERE name LIKE 't%'",
callback,
NULL,
&errmsg);
nlib_printf("\n");
if (result != SQLITE_OK) {
nlib_printf("%s\n", errmsg);
sqlite3_free(errmsg);
sqlite3_close(db);
return false;
}
// Sorts by price.
nlib_printf("> SELECT * FROM t_menu ORDER BY price ASC;\n");
result = sqlite3_exec(db,
"SELECT * FROM t_menu ORDER BY price ASC",
callback,
NULL,
&errmsg);
nlib_printf("\n");
if (result != SQLITE_OK) {
nlib_printf("%s\n", errmsg);
sqlite3_free(errmsg);
sqlite3_close(db);
return false;
}
sqlite3_close(db);
return true;
}
//
// sqlite3 in nlib uses nmalloc/nfree in libnx_oss.a.
// You have to link libnx_oss.a, and set up nmalloc.
//
#ifdef NLIB_HAS_VIRTUALMEMORY
extern "C" const NMallocSettings g_NMallocSettings = { NULL, 1024 * 1024 * 16, 0 };
#else
const size_t heapmem_size = 1024 * 1024 * 16;
NLIB_ALIGNAS(4096) static char heapmem[heapmem_size];
extern "C" const NMallocSettings g_NMallocSettings = { heapmem, heapmem_size, 0 };
#endif
NLIB_MAINFUNC