71 lines
1.7 KiB
C++
71 lines
1.7 KiB
C++
#include "../lib/sqlite3.hpp"
|
|
|
|
namespace marcelb::SQlite3 {
|
|
|
|
SQLite3::SQLite3(const string _path, bool _keepOpen) {
|
|
path = _path;
|
|
keepOpen = _keepOpen;
|
|
|
|
if (keepOpen) {
|
|
if (open()) {
|
|
throw string("[ERROR] Unable to open database ");
|
|
}
|
|
}
|
|
}
|
|
|
|
bool SQLite3::open() {
|
|
uint operationStatus = sqlite3_open(path.c_str(), &db);
|
|
return operationStatus != SQLITE_OK;
|
|
}
|
|
|
|
bool SQLite3::close() {
|
|
uint operationStatus = sqlite3_close(db);
|
|
db = NULL;
|
|
return operationStatus != SQLITE_OK;
|
|
}
|
|
|
|
map<string, vector<string>> SQLite3::query(const string& sql_command, const vector<string>& values) {
|
|
lock_guard<mutex> lock(io);
|
|
map<string, vector<string>> results;
|
|
|
|
if (!keepOpen) {
|
|
if (open()) {
|
|
throw string("[ERROR] Unable to open database ");
|
|
}
|
|
}
|
|
|
|
sqlite3_stmt* stmt;
|
|
if (sqlite3_prepare_v2(db, sql_command.c_str(), -1, &stmt, nullptr) != SQLITE_OK) {
|
|
throw string("[ERROR] Failed to prepare statement: ") + sqlite3_errmsg(db);
|
|
}
|
|
|
|
for (size_t i = 0; i < values.size(); ++i) {
|
|
sqlite3_bind_text(stmt, static_cast<int>(i + 1), values[i].c_str(), -1, SQLITE_TRANSIENT);
|
|
}
|
|
|
|
int columnCount = sqlite3_column_count(stmt);
|
|
while (sqlite3_step(stmt) == SQLITE_ROW) {
|
|
for (int i = 0; i < columnCount; ++i) {
|
|
const char* columnName = sqlite3_column_name(stmt, i);
|
|
const char* columnValue = (const char*)sqlite3_column_text(stmt, i);
|
|
results[columnName].push_back(columnValue ? columnValue : "NULL");
|
|
}
|
|
}
|
|
|
|
sqlite3_finalize(stmt);
|
|
|
|
if (!keepOpen) {
|
|
if (close()) {
|
|
throw string("[ERROR] Unable to close database ");
|
|
}
|
|
}
|
|
|
|
return results;
|
|
}
|
|
|
|
SQLite3::~SQLite3() {
|
|
close();
|
|
}
|
|
|
|
|
|
} |