1
0
forked from blue/pica
pica/database/mysql/mysql.cpp

86 lines
1.8 KiB
C++

#include "mysql.h"
MySQL::MySQL():
DBInterface(Type::mysql),
connection(),
login(),
password(),
database()
{
mysql_init(&connection);
}
MySQL::~MySQL() {
mysql_close(&connection);
}
void MySQL::connect(const std::string& path) {
if (state != State::disconnected)
return;
MYSQL* con = &connection;
MYSQL* res = mysql_real_connect(
con,
NULL,
login.c_str(),
password.c_str(),
database.empty() ? NULL : database.c_str(),
0,
path.c_str(),
0
);
if (res != con)
throw std::runtime_error(std::string("Error changing connecting: ") + mysql_error(con));
state = State::connected;
}
void MySQL::setCredentials(const std::string& login, const std::string& password) {
if (MySQL::login == login && MySQL::password == password)
return;
MySQL::login = login;
MySQL::password = password;
if (state == State::disconnected)
return;
MYSQL* con = &connection;
int result = mysql_change_user(
con,
login.c_str(),
password.c_str(),
database.empty() ? NULL : database.c_str()
);
if (result != 0)
throw std::runtime_error(std::string("Error changing credetials: ") + mysql_error(con));
}
void MySQL::setDatabase(const std::string& database) {
if (MySQL::database == database)
return;
MySQL::database = database;
if (state == State::disconnected)
return;
MYSQL* con = &connection;
int result = mysql_select_db(con, database.c_str());
if (result != 0)
throw std::runtime_error(std::string("Error changing db: ") + mysql_error(con));
}
void MySQL::disconnect() {
if (state == State::disconnected)
return;
MYSQL* con = &connection;
mysql_close(con);
mysql_init(con); //this is ridiculous!
}