带有MySQL连接器的VS Express 2013 C ++ stmt-> executeQuery()错误

时间:2014-07-22 07:58:17

标签: c++ mysql sql mysql-connector

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

现在,我正在尝试使用ResultSet获取行以从函数executeQuery中检索,但是此错误显示出来:
enter image description here
这是我的代码:

#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;
}

在输出窗格下,它也显示了这一点:

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之后调用堆栈并且它打破了,它显示了这个:

  

MySQLConnect.exe!main()第35行C ++

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

的行

如果您需要有关我的代码/设置的更多信息,请与我们联系。 提前谢谢!

1 个答案:

答案 0 :(得分:3)

傻了我,我发现了什么问题 我必须添加一行:

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());

我希望这有帮助!