sqlite_server/src/litedb.cc

72 lines
1.6 KiB
C++
Raw Normal View History

2025-03-13 20:26:17 +08:00
#include <litedb.h>
2025-03-13 21:59:22 +08:00
#include <iostream>
2025-03-13 20:26:17 +08:00
litedb::litedb(std::string &db_name) : stmt(nullptr), db(nullptr)
{
this->_db_path_name = std::move(db_name);
}
litedb::~litedb()
{
if (this->stmt)
sqlite3_finalize(this->stmt);
2025-03-13 21:59:22 +08:00
2025-03-13 20:26:17 +08:00
if (this->db)
sqlite3_close_v2(this->db);
}
Status litedb::litedb_open()
{
if (this->_db_path_name.empty())
{
return Status::STATUS_INNER_ERR;
}
if (this->db)
{
return Status::STATUS_OK;
}
2025-03-13 21:59:22 +08:00
int ret = sqlite3_open_v2(this->_db_path_name.c_str(), &this->db,
SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX | SQLITE_OPEN_READWRITE, nullptr);
2025-03-13 20:26:17 +08:00
if (ret != SQLITE_OK)
{
return Status::STATUS_INNER_ERR;
}
return Status::STATUS_OK;
2025-03-13 21:59:22 +08:00
}
Status litedb::exec_sql(std::string sql)
{
int ret = 0;
if (!this->is_db_open())
{
return Status::STATUS_DB_DB_NOT_OPEN;
}
ret = sqlite3_prepare_v3(this->get_db_handler(), sql.c_str(), sql.length(), 0, &this->stmt, nullptr);
if (ret != SQLITE_OK)
{
std::cerr << "failed to prepare statement\n";
sqlite3_finalize(this->stmt);
return Status::STATUS_DB_ERR_PREPARE;
}
ret = sqlite3_step(this->stmt);
if (ret != SQLITE_DONE)
{
std::cerr << "failed to step sqlite3\n";
sqlite3_finalize(this->stmt);
return Status::STATUS_DB_ERR_STEP;
}
sqlite3_finalize(this->stmt);
return Status::STATUS_OK;
}
/*the sql stmt for fetching all table's nanm*/
const std::string litedb::SQL_TEXT_FETCH_ALL_TABLE_NAME =
"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%';";