ZBLOG

c/c++ 写个mysql连接池 并编译测试验证

下面是一个简单的C++代码示例,展示如何使用连接池来连接和操作MySQL数据库。在编译和运行之前,请确保已经安装了MySQL C++ Connector。

  1. #include <mysql_driver.h>
  2. #include <mysql_connection.h>
  3. #include <cppconn/driver_manager.h>
  4. #include <cppconn/exception.h>
  5. #include <cppconn/prepared_statement.h>
  6. #include <mutex>
  7. #include <queue>
  8. class ConnectionPool {
  9. public:
  10. static ConnectionPool& getInstance() {
  11. static ConnectionPool instance;
  12. return instance;
  13. }
  14. std::shared_ptr<sql::Connection> getConnection() {
  15. std::unique_lock<std::mutex> lock(mutex_);
  16. if (connections_.empty()) {
  17. return nullptr; // 连接池中无可用连接
  18. }
  19. auto conn = connections_.front();
  20. connections_.pop();
  21. return conn;
  22. }
  23. void releaseConnection(std::shared_ptr<sql::Connection> conn) {
  24. std::unique_lock<std::mutex> lock(mutex_);
  25. connections_.push(conn);
  26. }
  27. private:
  28. ConnectionPool() : poolSize_(10) {
  29. try {
  30. sql::mysql::MySQL_Driver* driver;
  31. sql::ConnectOptionsMap connection_properties;
  32. // 设置连接属性,例如用户名、密码等
  33. connection_properties["hostName"] = "localhost";
  34. connection_properties["userName"] = "your_username";
  35. connection_properties["password"] = "your_password";
  36. // 创建驱动程序对象并建立连接
  37. driver = sql::mysql::get_mysql_driver_instance();
  38. for (int i = 0; i < poolSize_; ++i) {
  39. std::shared_ptr<sql::Connection> conn(driver->connect(connection_properties));
  40. connections_.push(conn);
  41. }
  42. } catch (sql::SQLException& e) {
  43. // 处理连接异常
  44. }
  45. }
  46. int poolSize_;
  47. std::queue<std::shared_ptr<sql::Connection>> connections_;
  48. std::mutex mutex_;
  49. };
  50. int main() {
  51. ConnectionPool& pool = ConnectionPool::getInstance();
  52. // 获取连接
  53. std::shared_ptr<sql::Connection> conn = pool.getConnection();
  54. if (conn != nullptr) {
  55. try {
  56. // 使用连接执行SQL语句等操作
  57. std::shared_ptr<sql::Statement> stmt(conn->createStatement());
  58. stmt->execute("USE your_database");
  59. stmt->execute("SELECT * FROM your_table");
  60. while (std::shared_ptr<sql::ResultSet> res(stmt->getResultSet())) {
  61. while (res->next()) {
  62. // 处理查询结果
  63. }
  64. res.reset(stmt->getMoreResults() ? stmt->getResultSet() : nullptr);
  65. }
  66. } catch (sql::SQLException& e) {
  67. // 处理数据库操作异常
  68. }
  69. // 释放连接到连接池中
  70. pool.releaseConnection(conn);
  71. }
  72. return 0;
  73. }

要编译和链接这个代码,可以使用以下命令:

  1. g++ -o connection_pool connection_pool.cpp -lmysqlcppconn -std=c++11

确保你的编译环境中已经正确安装了MySQL C++ Connector,并将其链接到你的程序中。然后就可以运行可执行文件 connection_pool 来测试验证连接池功能了。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=18225

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?