因此,我终于使VS 2013 C++使用连接器C和C++与mySQL连接,并且我知道这一点,因为我可以使用stmt-> execute()函数将表添加到数据库中。

现在,我尝试使用ResultSet获取行以从函数executeQuery检索,但是出现此错误:

这是我的代码:

#include <iostream>
#include <string>

#include "mysql_connection.h"
#include "mysql_driver.h"
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>

#define dbHOST "tcp://127.0.0.1:3306"
#define dbUSER "root"
#define dbPASS "root"
#define dbDB   "db_test"

using namespace std;
using namespace sql;

int main()
{
    sql::mysql::MySQL_Driver *driver;
    sql::Connection *con;
    sql::Statement *stmt;
    sql::ResultSet *res;

    driver = sql::mysql::get_driver_instance();
    con = driver->connect(dbHOST, dbUSER, dbPASS);

    stmt = con->createStatement();
    string query = "SELECT * FROM test";
    res = stmt->executeQuery(query.c_str());

    while (res->next()) {
        cout << "id = " << res->getInt(1);
        cout << ", label = '" << res->getString("label") << "'" << endl;
    }

    delete res;
    delete stmt;
    delete con;

    system("pause");
    return 0;
}

在输出 Pane 下,它也显示以下内容:
First-chance exception at 0x77661D4D in MySQLConnect.exe: Microsoft C++ exception: sql::SQLException at memory location 0x0088FB5C.

Unhandled exception at 0x77661D4D in MySQLConnect.exe: Microsoft C++ exception: sql::SQLException at memory location 0x0088FB5C.

在我按F5键并中断后,在调用堆栈下显示了以下内容:



第35行是 res = stmt-> executeQuery(query.c_str());

如果您需要有关我的代码/设置的更多信息,请告诉我。
提前致谢!

最佳答案

愚蠢的我,我发现了问题所在。
我必须添加一行:

stmt->execute("USE " dbDB);

在我可以对该数据库做任何进一步查询之前。该代码段现在如下所示:
stmt = con->createStatement();
stmt->execute("USE " dbDB);              // <-- This line, change dbDB to your own
string query = "SELECT * FROM test";     // <- before all of these below
res = stmt->executeQuery(query.c_str());

我希望这有帮助!

10-08 19:23