C++ MySQL 获取行

标签 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;
}

我想知道如何选择特定行、将它们打印出来或对其进行处理。

最佳答案

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

关于C++ MySQL 获取行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25887134/

相关文章:

c++ - 提高 C++ 中 ifstream 的性能

c++ - 在 C++ 中包装 C 函数和函数指针的最佳方法是什么?

php - 如何将逗号分隔的数据添加到数据库中

mysql - 如何修复 MySQL CREATE FUNCTION 查询?

sql - 如果我将数据库设计的这一部分的标识关系更改为非标识关系,这意味着什么?

C++队列容器

c++ - 将值输入到结构

php - isset 不适用于表单提交(实际上是数据库问题)

mysql - 初始记录后开始自动递增

java - 在方法内关闭数据库相关资源