| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- #include "sqlitedb.h"
- #include <iostream>
- #include <sstream>
- #include <sqlite3.h>
- SqliteDb::SqliteDb(const std::string& dbPath)
- {
- open(dbPath);
- }
- SqliteDb::~SqliteDb()
- {
- close();
- }
- bool SqliteDb::execute(const std::string &sql)
- {
- std::ignore = sql;
- return false;
- }
- std::string SqliteDb::readTable(const std::string &table, const std::vector<Param>& params)
- {
- std::string sql = "SELECT * FROM " + table;
- std::stringstream clause;
- std::string separator = "";
- for (const auto& [param, value] : params)
- {
- clause << separator << param << "=" << value;
- separator = " AND ";
- }
- clause.seekp(-5, std::ios_base::end);
- if (!params.empty())
- sql += " WHERE " + clause.str();
- sqlite3_stmt* stmt;
- int rc = sqlite3_prepare_v2(mDb, sql.c_str(), -1, &stmt, nullptr);
- if (rc != SQLITE_OK) {
- return std::string("SQL error: ") + sqlite3_errmsg(mDb);
- }
- int colCount = sqlite3_column_count(stmt);
- std::stringstream res;
- res << "[";
- while (sqlite3_step(stmt) == SQLITE_ROW) {
- separator = "";
- res << "{";
- for (int i = 0; i < colCount; i++) {
- const char* colName = sqlite3_column_name(stmt, i);
- const char* declType = sqlite3_column_decltype(stmt, i);
- const char* colValue = reinterpret_cast<const char*>(sqlite3_column_text(stmt, i));
- std::string type( declType );
- bool needQuote = (type == "TEXT" || type == "DATE" || !colValue);
- res << separator << colName << ":";
- if(needQuote)
- res << "\"";
- res << (colValue ? colValue : "null");
- if(needQuote)
- res << "\"";
- separator = ",";
- }
- res << "},";
- }
- res.seekp(-1, std::ios_base::end);
- res << "]";
- sqlite3_finalize(stmt);
- return res.str();
- }
- void SqliteDb::open(const std::string &dbPath)
- {
- char *zErrMsg = 0;
- int rc = sqlite3_open(dbPath.c_str(), &mDb);
- if (rc) {
- std::cerr << "Can't open database: " << sqlite3_errmsg(mDb) << std::endl;
- sqlite3_free(zErrMsg);
- }
- }
- void SqliteDb::close()
- {
- sqlite3_close(mDb);
- }
|