database_controller.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. /*
  2. * @Description: 数据库操作类
  3. * @Author: yct
  4. * @Date: 2020-07-15 14:08:46
  5. * @LastEditTime: 2020-07-22 19:10:53
  6. * @LastEditors: yct
  7. */
  8. #include "database_controller.h"
  9. //初始化
  10. Error_manager Database_controller::database_controller_init(std::string ip, int port, std::string username, std::string pass, std::string db_name, int conn_size)
  11. {
  12. //系统结束标记与连接池大小
  13. mb_exit = false;
  14. m_conn_pool_size = conn_size;
  15. m_db_param.connect_string = std::string("tcp://").append(ip).append(":").append(std::to_string(port));
  16. m_db_param.username = username;
  17. m_db_param.pass = pass;
  18. m_db_param.db_name = db_name;
  19. //mysql驱动
  20. if(m_mysql_driver == nullptr)
  21. {
  22. m_mysql_driver = sql::mysql::get_driver_instance();
  23. }
  24. if(m_mysql_driver == nullptr)
  25. {
  26. mb_initialized = false;
  27. return DB_INIT_FAILED;
  28. }
  29. //创建连接池
  30. fill_up_pool(m_conn_pool_size);
  31. //守护线程,检查连接状态并保持连接数量
  32. mp_guard_thread = new std::thread(&Database_controller::database_status_update, this);
  33. mb_initialized = true;
  34. if(check_status() == SUCCESS)
  35. {
  36. mb_connected = true;
  37. }else{
  38. mb_connected = false;
  39. }
  40. return SUCCESS;
  41. }
  42. //反初始化
  43. Error_manager Database_controller::database_controller_uninit()
  44. {
  45. mb_exit = true;
  46. if(mp_guard_thread!=nullptr)
  47. {
  48. if(mp_guard_thread->joinable())
  49. mp_guard_thread->join();
  50. delete mp_guard_thread;
  51. mp_guard_thread = nullptr;
  52. }
  53. return SUCCESS;
  54. }
  55. //数据库连接状态
  56. bool Database_controller::is_connected()
  57. {
  58. check_status();
  59. return mb_connected;
  60. }
  61. //****** 增删改查功能 *******
  62. //增
  63. Error_manager Database_controller::sql_insert(std::string sql_str)
  64. {
  65. // 1.检查状态,一旦无可用连接,则主动创建一个,若依然失败则直接返回错误
  66. Error_manager ec = check_status();
  67. if(ec != SUCCESS)
  68. {
  69. ec = fill_up_pool(1);
  70. }
  71. if(ec == SUCCESS)
  72. {
  73. // 从连接池获取连接
  74. m_conn_mutex.lock();
  75. boost::shared_ptr<sql::Connection> t_conn_ptr = m_db_conn_pool.front();
  76. m_db_conn_pool.pop();
  77. m_conn_mutex.unlock();
  78. // 使用该连接并在结束判断连接状态,将正常连接丢回队列
  79. if(t_conn_ptr!= nullptr && t_conn_ptr->isValid()){
  80. char buf[1024];
  81. memset(buf, 0, 1024);
  82. try
  83. {
  84. t_conn_ptr->setSchema(m_db_param.db_name);
  85. boost::scoped_ptr<sql::Statement> stmt(t_conn_ptr->createStatement());
  86. stmt->execute(sql_str);
  87. // 丢回队列
  88. if(t_conn_ptr!= nullptr && t_conn_ptr->isValid())
  89. {
  90. m_conn_mutex.lock();
  91. m_db_conn_pool.push(t_conn_ptr);
  92. m_conn_mutex.unlock();
  93. }
  94. return SUCCESS;
  95. }
  96. catch (sql::SQLException &e)
  97. {
  98. /* Use what() (derived from std::runtime_error) to fetch the error message */
  99. sprintf(buf, "# ERR: %s\n (MySQL error code: %d, SQLState: %s\nsql: %s", e.what(), e.getErrorCode(), e.getSQLState().c_str(), sql_str.c_str());
  100. usleep(1000* 3000);
  101. return Error_manager(DB_INSERT_FAILED, NEGLIGIBLE_ERROR, buf);
  102. }
  103. catch (std::runtime_error &e)
  104. {
  105. sprintf(buf, "# ERR: %s\n ERR: runtime_error in %s \nsql: %s",e.what(),__FILE__, sql_str.c_str());
  106. return Error_manager(DB_INSERT_FAILED, NEGLIGIBLE_ERROR, buf);
  107. }
  108. // catch (std::exception &e)
  109. // {
  110. // sprintf(buf, "# ERR: %s\n ERR: Standard exception in %s ",e.what(),__FILE__);
  111. // return Error_manager(DB_INSERT_FAILED, NEGLIGIBLE_ERROR, buf);
  112. // }
  113. }
  114. else
  115. {
  116. return DB_CONNECT_FAILED;
  117. }
  118. }else{
  119. return ec;
  120. }
  121. }
  122. //删
  123. Error_manager Database_controller::sql_delete(std::string sql_str)
  124. {
  125. // 1.检查状态,一旦无可用连接,则主动创建一个,若依然失败则直接返回错误
  126. Error_manager ec = check_status();
  127. if(ec != SUCCESS)
  128. {
  129. ec = fill_up_pool(1);
  130. }
  131. if(ec == SUCCESS)
  132. {
  133. // 从连接池获取连接
  134. m_conn_mutex.lock();
  135. boost::shared_ptr<sql::Connection> t_conn_ptr = m_db_conn_pool.front();
  136. m_db_conn_pool.pop();
  137. m_conn_mutex.unlock();
  138. // 使用该连接并在结束判断连接状态,将正常连接丢回队列
  139. if(t_conn_ptr!= nullptr && t_conn_ptr->isValid()){
  140. char buf[1024];
  141. memset(buf, 0, 1024);
  142. try
  143. {
  144. t_conn_ptr->setSchema(m_db_param.db_name);
  145. boost::scoped_ptr<sql::Statement> stmt(t_conn_ptr->createStatement());
  146. stmt->execute(sql_str);
  147. // 丢回队列
  148. if(t_conn_ptr!= nullptr && t_conn_ptr->isValid())
  149. {
  150. m_conn_mutex.lock();
  151. m_db_conn_pool.push(t_conn_ptr);
  152. m_conn_mutex.unlock();
  153. }
  154. return SUCCESS;
  155. }
  156. catch (sql::SQLException &e)
  157. {
  158. /* Use what() (derived from std::runtime_error) to fetch the error message */
  159. sprintf(buf, "# ERR: %s\n (MySQL error code: %d, SQLState: %s\nsql: %s", e.what(), e.getErrorCode(), e.getSQLState().c_str(), sql_str.c_str());
  160. return Error_manager(DB_DELETE_FAILED, NEGLIGIBLE_ERROR, buf);
  161. }
  162. catch (std::runtime_error &e)
  163. {
  164. sprintf(buf, "# ERR: %s\n ERR: runtime_error in %s \nsql: %s",e.what(),__FILE__, sql_str.c_str());
  165. return Error_manager(DB_DELETE_FAILED, NEGLIGIBLE_ERROR, buf);
  166. }
  167. }
  168. else
  169. {
  170. return DB_CONNECT_FAILED;
  171. }
  172. }else{
  173. return ec;
  174. }
  175. }
  176. //改
  177. Error_manager Database_controller::sql_update(std::string sql_str)
  178. {
  179. // 1.检查状态,一旦无可用连接,则主动创建一个,若依然失败则直接返回错误
  180. Error_manager ec = check_status();
  181. if(ec != SUCCESS)
  182. {
  183. ec = fill_up_pool(1);
  184. }
  185. if(ec == SUCCESS)
  186. {
  187. // 从连接池获取连接
  188. m_conn_mutex.lock();
  189. boost::shared_ptr<sql::Connection> t_conn_ptr = m_db_conn_pool.front();
  190. m_db_conn_pool.pop();
  191. m_conn_mutex.unlock();
  192. // 使用该连接并在结束判断连接状态,将正常连接丢回队列
  193. if(t_conn_ptr!= nullptr && t_conn_ptr->isValid()){
  194. char buf[1024];
  195. memset(buf, 0, 1024);
  196. try
  197. {
  198. t_conn_ptr->setSchema(m_db_param.db_name);
  199. boost::scoped_ptr<sql::Statement> stmt(t_conn_ptr->createStatement());
  200. int affected_rows = stmt->executeUpdate(sql_str);
  201. // 丢回队列
  202. if(t_conn_ptr!= nullptr && t_conn_ptr->isValid())
  203. {
  204. m_conn_mutex.lock();
  205. m_db_conn_pool.push(t_conn_ptr);
  206. m_conn_mutex.unlock();
  207. }
  208. if (affected_rows > 0)
  209. {
  210. return SUCCESS;
  211. }
  212. else
  213. {
  214. return DB_UPDATE_FAILED;
  215. }
  216. }
  217. catch (sql::SQLException &e)
  218. {
  219. /* Use what() (derived from std::runtime_error) to fetch the error message */
  220. sprintf(buf, "# ERR: %s\n (MySQL error code: %d, SQLState: %s\nsql: %s", e.what(), e.getErrorCode(), e.getSQLState().c_str(), sql_str.c_str());
  221. return Error_manager(DB_UPDATE_FAILED, NEGLIGIBLE_ERROR, buf);
  222. }
  223. catch (std::runtime_error &e)
  224. {
  225. sprintf(buf, "# ERR: %s\n ERR: runtime_error in %s \nsql: %s",e.what(),__FILE__, sql_str.c_str());
  226. return Error_manager(DB_UPDATE_FAILED, NEGLIGIBLE_ERROR, buf);
  227. }
  228. }
  229. else
  230. {
  231. return DB_CONNECT_FAILED;
  232. }
  233. }else{
  234. return ec;
  235. }
  236. }
  237. //查
  238. Error_manager Database_controller::sql_query(std::string sql_str, boost::shared_ptr< sql::ResultSet > &query_result)
  239. {
  240. // 1.检查状态,一旦无可用连接,则主动创建一个,若依然失败则直接返回错误
  241. Error_manager ec = check_status();
  242. if(ec != SUCCESS)
  243. {
  244. ec = fill_up_pool(1);
  245. }
  246. if(ec == SUCCESS)
  247. {
  248. // 从连接池获取连接
  249. m_conn_mutex.lock();
  250. boost::shared_ptr<sql::Connection> t_conn_ptr = m_db_conn_pool.front();
  251. // std::cout<<"conn handle: "<<t_conn_ptr<<std::endl;
  252. m_db_conn_pool.pop();
  253. // std::cout<<"conn handle after pop: "<<t_conn_ptr<<std::endl;
  254. m_conn_mutex.unlock();
  255. // 使用该连接并在结束判断连接状态,将正常连接丢回队列
  256. if(t_conn_ptr!= nullptr && t_conn_ptr->isValid()){
  257. char buf[1024];
  258. memset(buf, 0, 1024);
  259. try
  260. {
  261. t_conn_ptr->setSchema(m_db_param.db_name);
  262. boost::scoped_ptr< sql::Statement > stmt(t_conn_ptr->createStatement());
  263. query_result = boost::shared_ptr< sql::ResultSet >(stmt->executeQuery(sql_str));
  264. // 丢回队列
  265. if(t_conn_ptr!= nullptr && t_conn_ptr->isValid())
  266. {
  267. m_conn_mutex.lock();
  268. m_db_conn_pool.push(t_conn_ptr);
  269. m_conn_mutex.unlock();
  270. }
  271. // 检查结果
  272. if(query_result!=nullptr)
  273. {
  274. return SUCCESS;
  275. }else{
  276. return DB_QUERY_FAILED;
  277. }
  278. }
  279. catch (sql::SQLException &e)
  280. {
  281. /* Use what() (derived from std::runtime_error) to fetch the error message */
  282. sprintf(buf, "# ERR: %s\n (MySQL error code: %d, SQLState: %s\nsql: %s", e.what(), e.getErrorCode(), e.getSQLState().c_str(), sql_str.c_str());
  283. return Error_manager(DB_UPDATE_FAILED, NEGLIGIBLE_ERROR, buf);
  284. }
  285. catch (std::runtime_error &e)
  286. {
  287. sprintf(buf, "# ERR: %s\n ERR: runtime_error in %s \nsql: %s",e.what(),__FILE__, sql_str.c_str());
  288. return Error_manager(DB_UPDATE_FAILED, NEGLIGIBLE_ERROR, buf);
  289. }
  290. }else{
  291. return DB_CONNECT_FAILED;
  292. }
  293. }else{
  294. return ec;
  295. }
  296. }
  297. void Database_controller::database_status_update()
  298. {
  299. while(!mb_exit && mb_initialized)
  300. {
  301. std::cout<<"guard thread working."<<std::endl;
  302. // 检查连接状态,直到获得正常连接或队列为空为止
  303. check_status();
  304. fill_up_pool(m_conn_pool_size);
  305. usleep(1000*DB_UPDATE_INTERVAL_MILLI);
  306. }
  307. }
  308. // 检查连接状态
  309. Error_manager Database_controller::check_status()
  310. {
  311. std::lock_guard<std::mutex> lck(m_conn_mutex);
  312. while (m_db_conn_pool.size() > 0)
  313. {
  314. boost::shared_ptr<sql::Connection> t_conn_ptr = m_db_conn_pool.front();
  315. if (t_conn_ptr != nullptr && t_conn_ptr->isValid())
  316. {
  317. mb_connected = true;
  318. break;
  319. }
  320. else
  321. {
  322. mb_connected = false;
  323. m_db_conn_pool.pop();
  324. }
  325. }
  326. if(mb_connected)
  327. return SUCCESS;
  328. else
  329. return DB_CONNECT_FAILED;
  330. }
  331. // 补充连接
  332. Error_manager Database_controller::fill_up_pool(int add_num)
  333. {
  334. std::lock_guard<std::mutex> lck(m_conn_mutex);
  335. // 填充连接池
  336. int retry_count = 3;
  337. int added_num = 0;
  338. while (m_db_conn_pool.size() < m_conn_pool_size && added_num<add_num)
  339. {
  340. try
  341. {
  342. // 三次创建连接失败则暂时释放锁
  343. if (retry_count <= 0)
  344. {
  345. mb_connected = false;
  346. break;
  347. }
  348. boost::shared_ptr<sql::Connection> t_conn_ptr(m_mysql_driver->connect(m_db_param.connect_string, m_db_param.username, m_db_param.pass));
  349. if (t_conn_ptr != nullptr && t_conn_ptr->isValid())
  350. {
  351. m_db_conn_pool.push(t_conn_ptr);
  352. added_num++;
  353. }
  354. else
  355. {
  356. retry_count--;
  357. }
  358. }
  359. catch (sql::SQLException &e)
  360. {
  361. char buf[1024];
  362. memset(buf, 0, 1024);
  363. sprintf(buf, "# ERR: %s\n (MySQL error code: %d, SQLState: %s", e.what(), e.getErrorCode(), e.getSQLState().c_str());
  364. std::cout << buf << std::endl;
  365. retry_count--;
  366. }
  367. }
  368. m_conn_mutex.unlock();
  369. if(mb_connected)
  370. {
  371. return SUCCESS;
  372. }else{
  373. return DB_CONNECT_FAILED;
  374. }
  375. }