При подключении к MySQL из C ++ функция getString () работает неправильно - PullRequest
1 голос
/ 23 апреля 2020
#include <stdlib.h>
#include <iostream>
#include<mysql/jdbc.h>
#include<string>
/*
  Include directly the different
  headers from cppconn/ and mysql_driver.h + mysql_util.h
  (and mysql_connection.h). This will reduce your build time!
*/
#include "mysql_connection.h"

#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
//#pragma comment(lib,"mysqlcppconn8.lib")
using namespace std;

int main(void)
{
    cout << endl;
    cout << "Running 'SELECT 'Hello World!' >> AS _message'..." << endl;

        try {

        sql::Connection* con;
        sql::Statement* stmt;
        sql::ResultSet* res;

        /* Create a connection */
        sql::Driver* driver = get_driver_instance();
        con = driver->connect("tcp://127.0.0.1:3306", "root", "v3952003");
        /* Connect to the MySQL test database */
        con->setSchema("bank_db");

        stmt = con->createStatement();
        res = stmt->executeQuery("SELECT * from account");
        string bankCode="";
        while (res->next()) {
            cout << "\t... MySQL replies: " << endl;
            /* Access column data by alias or column name */
            cout << "No : "<<res->getInt(1) << endl;
            cout << "BankCode : " << res->getString(2) << endl;
            cout << "AccountNo : " << res->getString(3) << endl;
            cout << "CardNo : " << res->getString(4) << endl;
            cout << "Pwd : " << res->getString(5) << endl;
            cout << "Name : " << res->getString(6) << endl;
            cout << "Deposit : " << res->getInt(7) << endl;
            cout << "\t... MySQL says it again: ";
            /* Access column data by numeric offset, 1 is the first column */
        }
        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;
}

В этом коде getInt () возвращает правильное значение, но getString () работает неправильно.

getString () возвращает странные значения. Я не знаю, в чем проблема.

Я попытался отладить, установив точки останова в while ().

cout << "BankCode : " << res->getString(2) << endl; И вместо этой строки

String bankCode=""; написал это до того, как while (),

bankCode.append(res->getString(2));
cout<<bankCode<<endl;

и записали их в while (),

, но это тоже не работает.

Поскольку getString () не работает Возможно, он работает неправильно, поэтому бесполезно проливать код.

введите описание изображения здесь

...