1.标准目录
2.cmakeList.txt
cmake_minimum_required(VERSION 3.16)
project(MySql LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# 设置运行时库路径
set(CMAKE_INSTALL_RPATH "C:/Program Files/MySQL/MySQL Server 8.0/lib")
include_directories("C:/Program Files/MySQL/MySQL Server 8.0/include")
# target_link_libraries(MySql "C:/Program Files/MySQL/MySQL Server 8.0/lib/libmysql.lib")
# 查找指定目录下的所有库文件(这里假设库文件以.lib结尾)
file(GLOB LIB_FILES "C:/Program Files/MySQL/MySQL Server 8.0/lib/*.lib")
# 遍历并链接找到的库文件
foreach(LIB_FILE ${LIB_FILES})
target_link_libraries(MySql ${LIB_FILE})
endforeach()
add_executable(MySql main.cpp)
include(GNUInstallDirs)
install(TARGETS MySql
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
)
拷贝C:/Program Files/MySQL/MySQL Server 8.0/lib下文件到可执行程序下
3.测试代码
#include <iostream>
#include"mysql.h"
using namespace std;
int main()
{
cout << "mysq version:" <<mysql_get_client_info()<< endl;
// 初始化MySQL连接对象
MYSQL *conn = mysql_init(NULL);
if (conn == NULL) {
std::cerr << "mysql_init() failed" << std::endl;
return 1;
}
// 连接到MySQL数据库
if (mysql_real_connect(conn, "localhost", "root", "123456", "db01", 0, NULL, 0)== NULL) {
std::cerr << "mysql_real_connect() failed: " << mysql_error(conn) << std::endl;
mysql_close(conn);
return 1;
}
// 执行查询语句
if (mysql_query(conn, "SELECT * FROM tb_user")) {
std::cerr << "mysql_query() failed: " << mysql_error(conn) << std::endl;
mysql_close(conn);
return 1;
}
// 获取结果集
MYSQL_RES *result = mysql_store_result(conn);
if (result == NULL) {
std::cerr << "mysql_store_result() failed: " << mysql_error(conn) << std::endl;
mysql_close(conn);
return 1;
}
// 获取结果集中的行数和列数
int num_fields = mysql_num_fields(result);
MYSQL_ROW row;
while ((row = mysql_fetch_row(result))) {\
for (int i = 0; i < num_fields; i++) {
std::cout << row[i] << " ";
}
std::cout << std::endl;
}
// 释放结果集内存
mysql_free_result(result);
// 关闭数据库连接
mysql_close(conn);
return 0;
}