Visual Studio 2019编译C++项目使用MySQL Connector 8.0.26构建报错求助
问题描述
我从Connector/C++ 8.0.26官方页面下载了对应的库和头文件,逐一尝试所有版本后,项目构建阶段始终报错。
我使用的是Visual Studio 2019(版本号16.10.0),参考MySQL官网示例创建了一个简单的控制台应用,示例代码如下:
#include "mysql_connection.h" #include <cppconn/driver.h> #include <cppconn/exception.h> #include <cppconn/resultset.h> #include <cppconn/statement.h> using namespace std; int main(void) { cout << endl; cout << "Running 'SELECT 'Hello World!' AS _message'..." << endl; try { sql::Driver *driver; sql::Connection *con; sql::Statement *stmt; sql::ResultSet *res; /* Create a connection */ driver = get_driver_instance(); con = driver->connect("tcp://127.0.0.1:3306", "root", "root"); /* Connect to the MySQL test database */ con->setSchema("test"); stmt = con->createStatement(); res = stmt->executeQuery("SELECT 'Hello World!' AS _message"); while (res->next()) { cout << "\t... MySQL replies: "; /* Access column data by alias or column name */ cout << res->getString("_message") << endl; cout << "\t... MySQL says it again: "; /* Access column data by numeric offset, 1 is the first column */ cout << res->getString(1) << endl; } delete res; delete stmt; delete con; } catch (sql::SQLException &e) { cout << "# ERR: SQLException in " << __FILE__; cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << endl; cout << "# ERR: " << e.what(); cout << " (MySQL error code: " << e.getErrorCode(); cout << ", SQLState: " << e.getSQLState() << " )" << endl; } cout << endl; return EXIT_SUCCESS; }
我切换了32位/64位、Debug/Release等所有配置,均出现相同构建报错。我查阅了相关平台超过100篇同问题相关的帖子,尝试了所有给出的解决方案均无效。目前我还没试过的方案只有下载Visual Studio 2015来测试运行。
现在已经是2021年了,请问这真的是开发C++ MySQL简单应用的合理解决方案吗?还是我有其他操作没有做到位?
解决方案
不需要完全安装VS2015,你遇到的是典型的MSVC工具集ABI不兼容问题,MySQL 8.0.26版本的预编译Connector/C++默认用VS2015(v140)工具集编译,和VS2019默认的v142工具集不兼容,按以下步骤配置即可解决:
- 打开Visual Studio Installer,选择修改已安装的VS2019,切换到「单个组件」标签,勾选「MSVC v140 - VS 2015 C++ 生成工具(v14.00)」,安装完成后重启VS
- 打开项目属性页,在「常规」-「平台工具集」选项中选择「Visual Studio 2015 (v140)」,和Connector编译工具集保持一致
- 确认项目链接器配置符合要求:32位/64位和下载的Connector版本完全对应,Debug模式使用带
d后缀的Connector库、Release模式使用不带后缀的库,动态链接时附加依赖项添加mysqlcppconn.lib,静态链接时附加依赖项添加mysqlcppconn-static.lib同时在预处理器定义中添加STATIC_CONCPP - 确认项目「C/C++」-「代码生成」-「运行库」选项和Connector保持一致:默认预编译包使用
/MD(Release)、/MDd(Debug)运行时,不要选择/MT//MTd版本
如果以上配置完成后仍有报错,可以直接拉取Connector/C++源码用当前VS2019的v142工具集本地编译一次,生成的库可以完全适配当前开发环境,比更换整个IDE版本成本低很多。
内容的提问来源于stack exchange,提问作者Milad Abooali
相关产品推荐
相关产品推荐

