C ++ MySQL Fetch Row

时间:2014-09-17 09:41:37

标签: c++ mysql sql connect

我有这个小代码,我正在尝试连接数据库,工作正常,现在我想选择/创建一个表,这也很好,但我不能因为某种原因选择一个特定的行。我不想遍历所有内容,我只想选择例如列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;
}

我想知道,我如何选择特定行,打印出来或用它们做些什么。

1 个答案:

答案 0 :(得分:1)

选择行: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>