#include "opmysql.h" #ifndef _USING_MYSQL_51_LIB_ #include #include #include #include #include #include #endif #include #include #include "openjson.h" OpDatabase OpDatabase::m_instance; OpDatabase::OpDatabase() :m_pDbConnection(nullptr) { } OpDatabase::~OpDatabase() { //CloseDatabase(); } OpDatabase* OpDatabase::getInstance() { return &m_instance; } bool OpDatabase::OpenDatabase(const std::string& server /*= "127.0.0.1"*/, int dbport /*= 3306*/, const std::string& dbuser/* = "root"*/, const std::string& dbpasswd /*= "Hj57471000"*/, const std::string& database /*= "hjems"*/) { #ifndef _USING_MYSQL_51_LIB_ // 打开数据库 try { // 数据库连接配置 //std::string server = "tcp://127.0.0.1:3306"; //std::string dbuser = "root"; //std::string password = "Hj57471000"; std::string password = "L2ysc1s1kr"; //std::string database = "hjems"; // 创建连接 sql::mysql::MySQL_Driver* driver; driver = sql::mysql::get_mysql_driver_instance(); //m_pDbConnection.reset(driver->connect(server, dbuser, password)); m_pDbConnection = driver->connect(server, dbuser, password); if (!m_pDbConnection) { hloge("Failed to connect to database."); return false; } // 设置为使用指定数据库 m_pDbConnection->setSchema(database); return true; } catch (sql::SQLException& e) { std::ostringstream ss; ss << "SQLException: " << e.what(); ss<< " (MySQL error code: " << e.getErrorCode(); ss << ", SQLState: " << e.getSQLState() << " )"; hloge("Failed to connect to database: %s",ss.str().c_str()); return false; } #else bool ok = false; m_pDbConnection = mysql_init(NULL); //连接到MySQL服务器 if (!mysql_real_connect(m_pDbConnection, server.c_str(), dbuser.c_str(), dbpasswd.c_str(), database.c_str(), dbport, NULL, 0)) { hloge("MySQL connection error: %s", mysql_error(m_pDbConnection)); } else { ok = true; mysql_set_character_set(m_pDbConnection, "utf8"); } if (!ok) { hloge("Failed to connect to database."); } else { hlogd("new database connection created successfully!"); } return ok; #endif } // 关闭数据库连接 void OpDatabase::CloseDatabase() { #ifdef _USING_MYSQL_51_LIB_ mysql_close(m_pDbConnection); #else m_pDbConnection->close(); //delete m_pDbConnection; #endif } 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) { #ifndef _USING_MYSQL_51_LIB_ const char* insertSql = "INSERT INTO tbl_data (data_timestamp, data_type, FsuCode, data_content, topic, device_id) VALUES (?,?,?,?,?,?);"; // 创建预编译的prepared statement std::unique_ptr insertStmt(m_pDbConnection->prepareStatement(insertSql)); // 绑定插入数据的参数 insertStmt->setString(1, ts); insertStmt->setString(2, msg_type); insertStmt->setString(3, fsu); insertStmt->setString(4, content); insertStmt->setInt(5, topic); insertStmt->setInt(6, dev_id); // 执行插入操作 int rowsAffected = insertStmt->executeUpdate(); // 检查插入操作是否成功 if (rowsAffected > 0) { hlogi( "New message inserted successfully." ); } else { hloge( "No rows affected during insert operation." ); } #else #endif }