81 lines
1.9 KiB
C++
81 lines
1.9 KiB
C++
|
#include "mysqlutils.h"
|
||
|
|
||
|
#include <hv/hlog.h>
|
||
|
#include <sstream>
|
||
|
|
||
|
#include <QtSql/QSqlDatabase>
|
||
|
#include <QStringList>
|
||
|
|
||
|
MysqlUtils MysqlUtils::m_instance;
|
||
|
|
||
|
MysqlUtils::MysqlUtils()
|
||
|
:m_pDbConnection(nullptr)
|
||
|
{}
|
||
|
|
||
|
MysqlUtils::~MysqlUtils()
|
||
|
{
|
||
|
CloseDatabase();
|
||
|
}
|
||
|
|
||
|
MysqlUtils* MysqlUtils::getInstance()
|
||
|
{
|
||
|
return &m_instance;
|
||
|
}
|
||
|
|
||
|
bool MysqlUtils::OpenDatabase(const std::string& server, int dbport, const std::string& dbuser, const std::string& dbpasswd, const std::string& database)
|
||
|
{
|
||
|
// 打开数据库
|
||
|
try
|
||
|
{
|
||
|
if (m_pDbConnection!=nullptr)
|
||
|
{
|
||
|
if (m_pDbConnection->isValid())
|
||
|
{
|
||
|
hlogd("database already connected.");
|
||
|
return true;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
using namespace sql;
|
||
|
|
||
|
// 创建连接
|
||
|
sql::Driver* driver;
|
||
|
sql::ConnectOptionsMap connection_properties;
|
||
|
|
||
|
connection_properties["hostName"] = server.c_str();
|
||
|
connection_properties["userName"] = dbuser.c_str();
|
||
|
connection_properties["password"] = dbpasswd.c_str();
|
||
|
connection_properties["schema"] = database.c_str();
|
||
|
connection_properties["port"] = dbport;
|
||
|
connection_properties["OPT_RECONNECT"] = true;
|
||
|
|
||
|
driver = get_driver_instance();
|
||
|
m_pDbConnection = driver->connect(connection_properties);
|
||
|
|
||
|
if (!m_pDbConnection)
|
||
|
{
|
||
|
hloge("Failed to connect to database.");
|
||
|
return false;
|
||
|
}
|
||
|
|
||
|
hlogd("new database connection created successfully!");
|
||
|
|
||
|
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 MysqlUtils::CloseDatabase()
|
||
|
{
|
||
|
if (m_pDbConnection)
|
||
|
m_pDbConnection->close();
|
||
|
}
|