emsApplication/applications/ems_datahubs/opmysql.cpp

103 lines
2.4 KiB
C++

#include "opmysql.h"
#include <mysql_driver.h>
#include <mysql_connection.h>
#include <cppconn/prepared_statement.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include <cppconn/exception.h>
#include <hv/hlog.h>
#include <sstream>
#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, const std::string& dbuser, const std::string& database)
{
// 打开数据库
try
{
// 数据库连接配置
//std::string server = "tcp://127.0.0.1:3306";
//std::string dbuser = "root";
std::string password = "Hj57471000";
//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;
}
}
// 关闭数据库连接
void OpDatabase::CloseDatabase()
{
m_pDbConnection->close();
//delete m_pDbConnection;
}
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* insertSql = "INSERT INTO tbl_data (data_timestamp, data_type, FsuCode, data_content, topic, device_id) VALUES (?,?,?,?,?,?);";
// 创建预编译的prepared statement
std::unique_ptr<sql::PreparedStatement> 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." );
}
}