Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #pragma once
- #include <cppconn\driver.h>
- #include <cppconn\exception.h>
- #include <cppconn\resultset.h>
- #include <cppconn\statement.h>
- #include <assert.h>
- #include <thread>
- #include <chrono>
- namespace scratch
- {
- //byte RETRY_COUNTER = 5;
- class Statement
- {
- public:
- Statement::Statement(sql::Connection*& con) : _con(con)
- {
- _stmt = con->createStatement();
- }
- Statement::~Statement()
- {
- delete _stmt;
- }
- sql::ResultSet* read_db(std::string query)
- {
- try
- {
- if (_con)
- {
- if (!_con->isValid())
- if (!_con->reconnect())
- return nullptr;
- return _stmt->executeQuery(query);
- }
- }
- catch (sql::SQLException &e) {}
- return nullptr;
- }
- template <typename T>
- T get_column(sql::ResultSet* res, std::string column_name) {}
- template<>
- std::string get_column(sql::ResultSet* res, std::string column_name)
- {
- if (!res) return{};
- try
- {
- if (res->next())
- {
- auto string = res->getString(column_name.c_str());
- delete res;
- return string;
- }
- }
- catch (const std::exception&) {}
- return{};
- }
- template<>
- bool get_column(sql::ResultSet* res, std::string column_name)
- {
- if (!res) return{};
- try
- {
- if (res->next())
- {
- auto boolean = res->getBoolean(column_name.c_str());
- delete res;
- return boolean;
- }
- }
- catch (const std::exception&) {}
- return false;
- }
- template<>
- int get_column(sql::ResultSet* res, std::string column_name)
- {
- if (!res) return{};
- try
- {
- if (res->next())
- {
- auto integer = res->getInt(column_name.c_str());
- delete res;
- return integer;
- }
- }
- catch (const std::exception&) {}
- return 0;
- }
- bool alter_db(std::string query)
- {
- try
- {
- if (!_con->isValid())
- if (!_con->reconnect())
- return false;
- return !_stmt->execute(query.c_str());
- }
- catch (sql::SQLException &e) {}
- return false;
- }
- private:
- sql::Connection* _con;
- sql::Statement* _stmt;
- };
- class SQL
- {
- public:
- SQL::SQL(std::string host_name, std::string port, std::string username, std::string password)
- {
- _con = get_driver_instance()->connect(std::string("tcp://").append(host_name).append(":").append(port).c_str(), username.c_str(), password.c_str());
- if (!_con) return;
- _con->setSchema("scratch");
- _is_initialized = _con->isValid();
- }
- SQL::~SQL()
- {
- delete _con;
- }
- bool is_initialized()
- {
- return _is_initialized;
- }
- sql::Connection* get_connection()
- {
- return _con;
- }
- Statement* get_statement()
- {
- return new Statement(_con);
- }
- private:
- bool _is_initialized = false;
- sql::Connection* _con;
- };
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement