emsApplication/applications/library/libopdb/opdatabase.cpp

98 lines
2.4 KiB
C++
Raw Normal View History

2024-05-24 12:19:45 +08:00
#include "opdatabase.h"
#include <string>
#include <hv/hlog.h>
#include <sqlite3.h>
OpDatabase::OpDatabase()
:m_pSqliteDb(nullptr)
{
}
OpDatabase::~OpDatabase()
{
CloseDatabase();
}
bool OpDatabase::OpenDatabase(const std::string& db_file_path)
{
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ݿ<EFBFBD>
if (sqlite3_open(db_file_path.c_str(), &m_pSqliteDb) != SQLITE_OK)
{
hloge("Error opening database.");
return false;
}
return true;
}
// <20>ر<EFBFBD><D8B1><EFBFBD><EFBFBD>ݿ<EFBFBD><DDBF><EFBFBD><EFBFBD><EFBFBD>
void OpDatabase::CloseDatabase()
{
sqlite3_close(m_pSqliteDb);
}
void OpDatabase::InsertMessage(const std::string& ts, const std::string& msg_type,const std::string& fsu, const std::string& content, int topic, int dev_id)
{
const char* insertDataSQL = "INSERT INTO tbl_data (data_timestamp, data_type, FsuCode, data_content, topic, device_id) VALUES (?,?,?,?,?,?);";
sqlite3_stmt* statement;
if (sqlite3_prepare_v2(m_pSqliteDb, insertDataSQL, -1, &statement, nullptr) == SQLITE_OK)
{
// <20>󶨲<EFBFBD><F3B6A8B2><EFBFBD>
sqlite3_bind_text(statement, 1, ts.c_str(), -1, SQLITE_STATIC);
sqlite3_bind_text(statement, 2, msg_type.c_str(), -1, SQLITE_STATIC);
sqlite3_bind_text(statement, 3, fsu.c_str(), -1, SQLITE_STATIC);
sqlite3_bind_blob(statement, 4, content.c_str(), content.size(), SQLITE_STATIC);
//sqlite3_bind_text(statement, 4, content.c_str(), -1, SQLITE_STATIC);
sqlite3_bind_int(statement, 5, topic);
sqlite3_bind_int(statement, 6, dev_id);
// ִ<><D6B4><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
if (sqlite3_step(statement) != SQLITE_DONE)
{
hloge("Error inserting data.");
}
// <20>ͷ<EFBFBD><CDB7><EFBFBD>Դ
sqlite3_finalize(statement);
}
}
bool OpDatabase::QueryUser(const std::string& uname, const std::string& passwd)
{
const char* queryDataSQL = "SELECT * FROM tbl_user WHERE uid=?;";
sqlite3_stmt * statement;
if (sqlite3_prepare_v2(m_pSqliteDb, queryDataSQL, -1, &statement, nullptr) == SQLITE_OK)
{
// <20>󶨲<EFBFBD><F3B6A8B2><EFBFBD>
sqlite3_bind_text(statement, 1, uname.c_str(), -1, SQLITE_STATIC);
// ִ<><D6B4><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
if (sqlite3_step(statement) != SQLITE_DONE)
{
hlogw("Error query user %s", uname.c_str());
}
else
{
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
while (sqlite3_step(statement) == SQLITE_ROW)
{
hlogi("Userid: %s", sqlite3_column_text(statement, 0));
hlogi("UserName: %s", sqlite3_column_text(statement, 1));
hlogi("UserSalt: %s", sqlite3_column_text(statement, 2));
hlogi("UserPasswd: %s", sqlite3_column_text(statement, 3));
}
}
// <20>ͷ<EFBFBD><CDB7><EFBFBD>Դ
sqlite3_finalize(statement);
return true;
}
return false;
}