123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- /*
- * @Description: 数据库操作类
- * @Author: yct
- * @Date: 2020-07-14 14:09:35
- * @LastEditTime: 2020-07-18 23:57:10
- * @LastEditors: yct
- */
- #ifndef DATABASE_CONTROLLER_HH
- #define DATABASE_CONTROLLER_HH
- #include <mysql_driver.h>
- #include <mysql_connection.h>
- #include <cppconn/driver.h>
- #include <cppconn/exception.h>
- #include <cppconn/resultset.h>
- #include <cppconn/statement.h>
- #include "../tool/singleton.h"
- #include "../error_code/error_code.h"
- #include <stdio.h>
- #include <mutex>
- #include <queue>
- #include <thread>
- #include <atomic>
- #include <unistd.h>
- #include <string.h>
- #include <iostream>
- #include <cstddef>
- #include <boost/shared_ptr.hpp>
- #define DB_UPDATE_INTERVAL_MILLI 20000
- class Database_controller : public Singleton<Database_controller>
- {
- // 子类必须把父类设定为友元函数,这样父类才能使用子类的私有构造函数。
- friend class Singleton<Database_controller>;
- public:
- typedef struct DB_PARAM
- {
- std::string connect_string;
- std::string username;
- std::string pass;
- std::string db_name;
- } db_param;
- // 必须关闭拷贝构造和赋值构造,只能通过 get_instance 函数来进行操作唯一的实例。
- Database_controller(const Database_controller &) = delete;
- Database_controller &operator=(const Database_controller &) = delete;
- ~Database_controller() = default;
- //初始化
- Error_manager database_controller_init(std::string ip, int port, std::string username, std::string pass, std::string db_name, int conn_size=5);
- //反初始化
- Error_manager database_controller_uninit();
- //数据库连接状态
- bool is_connected();
- //****** 增删改查功能 *******
- //增
- Error_manager sql_insert(std::string sql_str);
- //删
- Error_manager sql_delete(std::string sql_str);
- //改
- Error_manager sql_update(std::string sql_str);
- //查
- Error_manager sql_query(std::string sql_str, boost::shared_ptr< sql::ResultSet > &query_result);
- private:
- // 父类的构造函数必须保护,子类的构造函数必须私有。
- Database_controller() = default;
- // 守护线程,维持连接数量,以及自身状态更新
- void database_status_update();
- // 检查连接状态
- Error_manager check_status();
- // 补充连接
- Error_manager fill_up_pool(int add_num);
- private:
- //mysql驱动句柄
- sql::Driver * m_mysql_driver;
- //连接状态
- std::atomic_bool mb_connected;
- //初始化状态
- std::atomic_bool mb_initialized;
- //系统关闭标记
- std::atomic_bool mb_exit;
- //连接池访问锁
- std::mutex m_conn_mutex;
- //数据库连接池
- std::queue< boost::shared_ptr< sql::Connection> > m_db_conn_pool;
- //守护线程
- std::thread *mp_guard_thread;
- //连接池大小
- int m_conn_pool_size;
- //连接参数
- db_param m_db_param;
- };
- #endif // !DATABASE_CONTROLLER_HH
|