sqlitedb.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #include "sqlitedb.h"
  2. #include <iostream>
  3. #include <sstream>
  4. #include <sqlite3.h>
  5. SqliteDb::SqliteDb(const std::string& dbPath)
  6. {
  7. open(dbPath);
  8. }
  9. SqliteDb::~SqliteDb()
  10. {
  11. close();
  12. }
  13. bool SqliteDb::execute(const std::string &sql)
  14. {
  15. std::ignore = sql;
  16. return false;
  17. }
  18. std::string SqliteDb::readTable(const std::string &table, const std::vector<Param>& params)
  19. {
  20. std::string sql = "SELECT * FROM " + table;
  21. std::stringstream clause;
  22. std::string separator = "";
  23. for (const auto& [param, value] : params)
  24. {
  25. clause << separator << param << "=" << value;
  26. separator = " AND ";
  27. }
  28. clause.seekp(-5, std::ios_base::end);
  29. if (!params.empty())
  30. sql += " WHERE " + clause.str();
  31. sqlite3_stmt* stmt;
  32. int rc = sqlite3_prepare_v2(mDb, sql.c_str(), -1, &stmt, nullptr);
  33. if (rc != SQLITE_OK) {
  34. return std::string("SQL error: ") + sqlite3_errmsg(mDb);
  35. }
  36. int colCount = sqlite3_column_count(stmt);
  37. std::stringstream res;
  38. res << "[";
  39. while (sqlite3_step(stmt) == SQLITE_ROW) {
  40. separator = "";
  41. res << "{";
  42. for (int i = 0; i < colCount; i++) {
  43. const char* colName = sqlite3_column_name(stmt, i);
  44. const char* declType = sqlite3_column_decltype(stmt, i);
  45. const char* colValue = reinterpret_cast<const char*>(sqlite3_column_text(stmt, i));
  46. std::string type( declType );
  47. bool needQuote = (type == "TEXT" || type == "DATE" || !colValue);
  48. res << separator << colName << ":";
  49. if(needQuote)
  50. res << "\"";
  51. res << (colValue ? colValue : "null");
  52. if(needQuote)
  53. res << "\"";
  54. separator = ",";
  55. }
  56. res << "},";
  57. }
  58. res.seekp(-1, std::ios_base::end);
  59. res << "]";
  60. sqlite3_finalize(stmt);
  61. return res.str();
  62. }
  63. void SqliteDb::open(const std::string &dbPath)
  64. {
  65. char *zErrMsg = 0;
  66. int rc = sqlite3_open(dbPath.c_str(), &mDb);
  67. if (rc) {
  68. std::cerr << "Can't open database: " << sqlite3_errmsg(mDb) << std::endl;
  69. sqlite3_free(zErrMsg);
  70. }
  71. }
  72. void SqliteDb::close()
  73. {
  74. sqlite3_close(mDb);
  75. }