#include "DB.h" #include "Exception.h" using namespace std; DB::DB(const string & path) { sqlite3 * db = NULL; int ret = sqlite3_open_v2(path.c_str(), &db, SQLITE_OPEN_READWRITE, NULL); this->db = { db, [] (sqlite3 * db) { sqlite3_close_v2(db); }, }; if (ret != SQLITE_OK) throw Exception("sqlite3_open_v2: %d", ret); } DBStatement DB::prepare(const string & query) { return DBStatement(*this, query); } DBStatement::DBStatement(DB & db, const string & query) : db(db) { sqlite3_stmt * stmt = NULL; int ret = sqlite3_prepare_v2(this->db.db.get(), query.c_str(), query.size(), &stmt, NULL); this->stmt = { stmt, [] (sqlite3_stmt * stmt) { sqlite3_finalize(stmt); }, }; if (ret != SQLITE_OK) throw Exception("sqlite3_prepare_v2: %d", ret); } DBStatement & DBStatement::bind(const string & text) { int ret = sqlite3_bind_text(this->stmt.get(), this->param_index, text.data(), text.size(), NULL); if (ret != SQLITE_OK) throw Exception("sqlite3_bind_text: %d", ret); this->param_index++; return *this; } DBStatement & DBStatement::bind(const int & number) { int ret = sqlite3_bind_int(this->stmt.get(), this->param_index, number); if (ret != SQLITE_OK) throw Exception("sqlite3_bind_int: %d", ret); this->param_index++; return *this; } DBStatement & DBStatement::unbind() { this->param_index = 1; return *this; } void DBStatement::execute() { int ret = sqlite3_step(this->stmt.get()); if (ret != SQLITE_DONE) throw Exception("sqlite3_step: %d", ret); }