C++ MySQL Fetch Row

rnmwe5a2  于 2023-05-16  发布在  Mysql
关注(0)|答案(1)|浏览(119)

我有这个小代码,我试图连接到一个数据库,它工作正常,现在我想选择/创建一个表,这也很好,但我不能出于任何原因选择一个特定的行。我不想循环遍历所有内容,我只想选择例如。列id的第6行。

/* Standard C++ includes */
#include <stdlib.h>
#include <iostream>
#include <string>

/*
Include directly the different
headers from cppconn/ and mysql_driver.h + mysql_util.h
MySQL Connector/C++ Complete Example 2
37
(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>

using namespace std;

int main(void)
{
    try {
        sql::Driver *driver;
        sql::Connection *con;
        sql::Statement *stmt;
        sql::ResultSet *res;

        /* Create a connection */
        driver = get_driver_instance();
        con = driver->connect("tcp://127.0.0.1:3306", "root", "root");

        /* Connect to the MySQL test database */
        con->setSchema("server_database");

        stmt = con->createStatement();
        stmt->execute("CREATE TABLE testit(id INT, label CHAR(1))");
        stmt->execute("INSERT INTO testit(id, label) VALUES (1, 'a')");
        stmt->execute("INSERT INTO testit(id, label) VALUES (2, 'b')");
        stmt->execute("INSERT INTO testit(id, label) VALUES (3, 'c')");
        res = stmt->executeQuery("SELECT id, label FROM testit ORDER BY id ASC");
    }
    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;
    int aasd;
    std::cin >> aasd;
    return EXIT_SUCCESS;
}

我想知道,我如何选择特定的行,打印出来或做一些与他们。

qco9c6ql

qco9c6ql1#

要选择行,请执行以下操作:n

SELECT id FROM testit LIMIT 1 OFFSET n-1;

在C++中:

int n=6;

 // build the string query
 std::ostringstream oss;
 oss << "SELECT id FROM testit LIMIT 1 OFFSET " << n-1;
 std::string query = oss.str();

 res = stmt->executeQuery(query);
 cout << "id = '" << res->getInt(1) << "'" << endl;

别忘了:

#include <string>
#include <sstream>

相关问题