不能从mysql读取结果

Cant read result from mysql

本文关键字:结果 读取 mysql 不能      更新时间:2023-10-16

我使用visual c++,我已经链接到库c++连接器(MySQL连接器c++ 1.1.7)和boost (boost_1_61_0)。

我使用32位连接器mysql, 64位连接器不工作。

我有windows 10(64位)

它编译。

但是当调试器到达cout << res->getString(1) << endl;行时它崩溃了,示例取自https://dev.mysql.com/doc/connector-cpp/en/connector-cpp-examples-complete-example-1.html

代码:

#include <stdlib.h>
#include <iostream>

#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 * from cars" << 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://localhost:3306", "root", "*****");
    /* Connect to the MySQL test database */
    con->setSchema("sakila");
    stmt = con->createStatement();
    res = stmt->executeQuery("SELECT * from cars");
    while (res->next()) {
        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;
}

错误信息:

Unhandled exception at 0x01327EA6 (msvcp120d.dll) in cppMySql.exe: 0xC0000005: Access violation reading location 0xCCCCCCCC

在查看了我在评论中提到的原始解决方案后,我设法重现了您的情况&我发现我得到了完全相同的错误。这就是我解决它的方法:

cout << res->getString(1).c_str() << endl;