|
| 1 | +#include <sqlite3.h> |
| 2 | +#include <stdarg.h> |
| 3 | + |
| 4 | +#include <filesystem> |
| 5 | +#include <iostream> |
| 6 | +#include <unordered_map> |
| 7 | + |
| 8 | +using namespace std; |
| 9 | +namespace fs = std::filesystem; |
| 10 | + |
| 11 | +class clsDb { |
| 12 | + private: |
| 13 | + sqlite3 *db; |
| 14 | + unordered_map<string, unordered_map<string, string>> dbMap; |
| 15 | + |
| 16 | + void setDbMap() { |
| 17 | + sqlite3_stmt *stmt; |
| 18 | + sqlite3_prepare_v2(db, |
| 19 | + "select name from sqlite_master where type='table'", |
| 20 | + -1, &stmt, 0); |
| 21 | + while (sqlite3_step(stmt) == SQLITE_ROW) { |
| 22 | + string table = (const char *)sqlite3_column_text(stmt, 0); |
| 23 | + sqlite3_stmt *stmt2; |
| 24 | + sqlite3_prepare_v2(db, ("pragma table_info(" + table + ")").c_str(), |
| 25 | + -1, &stmt2, 0); |
| 26 | + while (sqlite3_step(stmt2) == SQLITE_ROW) |
| 27 | + dbMap[table][(const char *)sqlite3_column_text(stmt2, 1)] = |
| 28 | + (const char *)sqlite3_column_text(stmt2, 2); |
| 29 | + |
| 30 | + sqlite3_finalize(stmt2); |
| 31 | + } |
| 32 | + sqlite3_finalize(stmt); |
| 33 | + } |
| 34 | + |
| 35 | + public: |
| 36 | + void insert(const string &table, const string &columns, ...) { |
| 37 | + va_list args; |
| 38 | + va_start(args, columns); |
| 39 | + short n = 0; |
| 40 | + for (int i = 0; i < columns.length(); i++) |
| 41 | + if (columns[i] == ',') n++; |
| 42 | + |
| 43 | + string command = "insert into users (" + columns + ") values ("; |
| 44 | + for (int i = 0; i < n; i++) command += "?, "; |
| 45 | + command += "?);"; |
| 46 | + cout << command << endl; |
| 47 | + |
| 48 | + sqlite3_stmt *stmt; |
| 49 | + sqlite3_prepare_v2(db, command.c_str(), -1, &stmt, 0); |
| 50 | + |
| 51 | + sqlite3_finalize(stmt); |
| 52 | + |
| 53 | + va_end(args); |
| 54 | + } |
| 55 | + clsDb(const string &path, const string &command) { |
| 56 | + sqlite3_open(path.c_str(), &db); |
| 57 | + sqlite3_exec(db, command.c_str(), 0, 0, 0); |
| 58 | + setDbMap(); |
| 59 | + } |
| 60 | +}; |
| 61 | + |
| 62 | +int main(int argc, char *argv[]) { |
| 63 | + string path = fs::canonical(argv[0]).parent_path().string() + '/'; |
| 64 | + |
| 65 | + clsDb db( |
| 66 | + path + "test.db", //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! |
| 67 | + "create table if not exists users(id integer primary key, username " |
| 68 | + "text, password blob); create table if not exists projects(id integer " |
| 69 | + "primary key, ownerId integer, prjName text, dir text, dirTree text)"); |
| 70 | + db.insert("table", "username, password", "kurwa", "aboba"); |
| 71 | +} |
0 commit comments