gpt4 book ai didi

C++ MySQL 获取行

转载 作者:行者123 更新时间:2023-11-28 06:41:26 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com