#include "opdatabase.h" #include #include #include OpDatabase::OpDatabase() :m_pSqliteDb(nullptr) { } OpDatabase::~OpDatabase() { CloseDatabase(); } bool OpDatabase::OpenDatabase(const std::string& db_file_path) { // 打开数据库 if (sqlite3_open(db_file_path.c_str(), &m_pSqliteDb) != SQLITE_OK) { hloge("Error opening database."); return false; } return true; } // 关闭数据库连接 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) { // 绑定参数 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); // 执行语句 if (sqlite3_step(statement) != SQLITE_DONE) { hloge("Error inserting data."); } // 释放资源 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) { // 绑定参数 sqlite3_bind_text(statement, 1, uname.c_str(), -1, SQLITE_STATIC); // 执行语句 if (sqlite3_step(statement) != SQLITE_DONE) { hlogw("Error query user %s", uname.c_str()); } else { // 遍历结果集 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)); } } // 释放资源 sqlite3_finalize(statement); return true; } return false; }