我想构建一个 C++ 程序来创建用户并将其保存到数据库(mysql)。我使用 Cmake 进行编译,使用 VSCode 作为 IDE。我已经安装了 MYSQL、MYSQL C++ 连接器。但是我的 IDE 说
#include <mysql/cppconn> ...
无法打开源文件。
这是我的数据库类的头文件:
#ifndef DATABASE_HPP
#define DATABASE_HPP
#include <mysql_driver.h>
#include <mysql_connection.h>
#include <cppconn/prepared_statement.h>
#include <cppconn/statement.h>
#include <cppconn/resultset.h>
#include <memory>
#include <string>
class Database {
public:
// Constructor to initialize database connection
Database();
// Method to add a new account to the database
void AddAccount(int accountID, const std::string& name, double balance, const std::string& password);
// Method to update the account balance after a transaction
void UpdateBalance(int accountID, double new_balance);
private:
sql::mysql::MySQL_Driver *driver;
std::unique_ptr<sql::Connection> con;
};
#endif
这是我的根目录
CmakeLists.txt
文件:
cmake_minimum_required(VERSION 3.25.0)
set(This Castle)
project(${This} C CXX)
set(CMAKE_C_STANDARD 99)
set(CMAKE_CXX_STANDARD 23)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
# Enable testing
enable_testing()
# Add GoogleTest subdirectory
add_subdirectory(googletest)
# Include directory for your headers
include_directories(${CMAKE_SOURCE_DIR}/include)
# Find OpenSSL package (make sure OpenSSL is installed and the path is correct)
find_package(OpenSSL REQUIRED)
include_directories(${OPENSSL_INCLUDE_DIR})
# Find MySQL Connector/C++ package
include_directories("C:/Program Files/MySQL/MySQL Connector C++ 9.0/include/mysql")
link_directories("C:/Program Files/MySQL/MySQL Connector C++ 9.0/lib64")
# Include MySQL Connector/C++ directories
include_directories(${MYSQLCONNECTORCPP_INCLUDE_DIRS})
# Your source and header files
set(Headers
include/account.hpp
include/security.hpp
include/transaction.hpp
include/auditLog.hpp
)
set(Sources
src/account.cpp
src/security.cpp
src/transaction.cpp
src/auditLog.cpp
)
# Create a static library
add_library(${This} STATIC ${Sources} ${Headers})
# Link OpenSSL and MySQL Connector libraries to your static library
target_link_libraries(${This} PUBLIC OpenSSL::SSL OpenSSL::Crypto ${MYSQLCONNECTORCPP_LIBRARIES})
# Add subdirectory for tests
add_subdirectory(tests)
我确保MYSQL C++ Connector的路径包含
mysql_driver.h
、cppconn
目录和其他必要的头文件,但它仍然无法工作。
提前感谢您的帮助。
从版本 8.3.0 开始,MySQL 连接器附带了 您链接到的一组很好的 CMake 目标:
set(mysql-concpp_DIR "C:/Program Files/MySQL/MySQL Connector C++ 9.0")
find_package(mysql-concpp REQUIRED)
target_link_libraries(${This} PUBLIC mysql::concpp)