1、下载MySQL Connector/C++,我这里下载的是debug版本,下载链接MySQL :: Download MySQL Connector/C++ (Archived Versions)
2、解压并且放到MySQL文件夹中,便于使用
3、打开vs2022,右键项目,点击属性
4、在 “C/C++” -> “常规” -> “附加包含目录” 中,添加Connector/C++的include目录
5、在 “链接器” -> “常规” -> “附加目录” 中,添加Connector/C++的lib64/vs14/debug目录
6、在 “链接器” -> “输入” -> “附加依赖项” 中,输入mysqlcppconn.lib
7、在Connector/C++的lib64目录下,找到libcrypto-1_1-x64.dll和libssl-1_1-x64.dll这两个文件,并且将其复制到项目的.sln文件同目录下
8、在Connector/C++的lib64\debug目录下,找到mysqlcppconn-9-vs14.dll和libcrypto-1_1-x64.dll,将其复制到项目x64目录下的debug或者release文件夹下(根据不同模式放入不同文件夹)
9、头文件:#include <mysql/jdbc>
10、测试代码
void test_connnect_sql() {SetConsoleOutputCP(CP_UTF8); //设置编码格式,避免mysql中的中文数据乱码try {sql::mysql::MySQL_Driver* driver;sql::Connection* con = nullptr;// 获取 MySQL 驱动实例driver = sql::mysql::get_mysql_driver_instance();std::cout << "Attempting to connect..." << std::endl;// 尝试连接数据库con = driver->connect("tcp://127.0.0.1:3306", "root", "1111");std::cout << "Connected successfully!" << std::endl;// 选择数据库con->setSchema("map_test");// 执行 SQL 查询sql::Statement* stmt = con->createStatement();sql::ResultSet* res = stmt->executeQuery("select * from phone_info");// 输出查询结果while (res->next()) {//cout << res->getString("phone") << "," <<res->getString("name") << endl;string phone = res->getString("phone");string name = res->getString("name");cout << phone << "," << name << endl;}//释放资源delete res;delete stmt;delete con;}catch (sql::SQLException& e) {std::cerr << "SQL Exception: " << e.what() << std::endl;}catch (std::exception& e) {std::cerr << "Exception: " << e.what() << std::endl;}
}