温馨提示×

CMake中MySQL连接池的配置

小樊
82
2024-09-05 21:08:34
栏目: 云计算

在CMake中配置MySQL连接池,首先需要确保已经安装了MySQL和相关的开发库

  1. 创建一个新的CMake项目,或者在现有项目中添加以下内容:

  2. 在项目的CMakeLists.txt文件中,找到或添加以下内容:

cmake_minimum_required(VERSION 3.0)
project(MySQLConnectionPool)

set(CMAKE_CXX_STANDARD 11)

# 添加MySQL连接器库
find_package(MySQLConnectorCPP REQUIRED)
include_directories(${MYSQL_CONNECTOR_CPP_INCLUDE_DIRS})

add_executable(MySQLConnectionPool main.cpp)

# 链接MySQL连接器库
target_link_libraries(MySQLConnectionPool ${MYSQL_CONNECTOR_CPP_LIBRARIES})

这里,我们使用find_package命令来查找MySQL连接器库。如果找到了库,我们将包含目录添加到项目中,并将库链接到可执行文件。

  1. 在项目中创建一个名为main.cpp的源文件,并添加以下内容:
#include<iostream>
#include<mysqlx/xdevapi.h>

int main() {
    const std::string url = "mysqlx://username:password@localhost";
    const std::string schema_name = "test_schema";

    try {
        mysqlx::Session session(url);
        mysqlx::Schema schema = session.getSchema(schema_name);

        // 创建一个表
        schema.createCollection("test_collection");

        // 插入一些数据
        mysqlx::Collection collection = schema.getCollection("test_collection");
        collection.add(R"({"name": "John", "age": 30})").execute();

        // 查询数据
        mysqlx::TableSelect select = collection.select();
        mysqlx::RowResult result = select.execute();

        // 输出查询结果
        std::cout << "Query result:"<< std::endl;
        for (const auto &row : result) {
            std::cout<< row[0].get<std::string>()<< std::endl;
        }
    } catch (const std::exception &e) {
        std::cerr << "Error: " << e.what()<< std::endl;
        return 1;
    }

    return 0;
}

这个示例代码展示了如何使用MySQL连接器库创建一个连接池,连接到MySQL数据库,并执行一些基本操作。

  1. 编译并运行项目:
mkdir build
cd build
cmake ..
make
./MySQLConnectionPool

这将编译项目并运行生成的可执行文件。如果一切正常,你应该能看到查询结果输出。

0