如果从官方直接下载的库使用时遇到类似如下的问题:
原因是官方提供的库文件版本与需要的库版本不匹配,提供的debug版本使用的是MT版本,在debug模式下会出现内存错误,导致crash。
TestC.exe中的...dll有未经处理的异常:读取位置时发生访问冲突。
那么可能需要自己手动编译源码(参考编译MySQL Connector/C++的资料)啦:
重新设置包含目录和库目录(实际中请把想要的头文件和库文件最好放到自己的工程目录里的第三方库或头文件如Libs之类的目录下,保证工程的可一致性,而不是像这里这样F:\Tools\....这样):
重新编译运行:
#include <stdlib.h> #include <iostream> #include <driver/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 << "Running 'SELECT 'Hello World!' AS _message'..." << endl; try { sql::Driver *driver; sql::Connection *con; sql::Statement *stmt; sql::ResultSet *res; /* 连接mysql服务器 */ driver = get_driver_instance(); con = driver->connect("tcp://127.0.0.1:3307", "root", "*****"); con->setSchema("test"); stmt = con->createStatement(); res = stmt->executeQuery("SELECT 'Hello World!' AS _message"); while (res->next()) { //通过列别名访问 cout << res->getString("_message") << endl; //通过列偏移 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; } cin.get(); return EXIT_SUCCESS; }
MySQL Connector/C++文档: