mysql C ++选择所有列中的所有行

时间:2016-01-09 23:40:55

标签: c++ mysql

我正在尝试从表中的所有列中选择所有行并将它们输出到字符串,我尝试递增结果集并将每行附加到字符串但不起作用。

我可以让它工作的唯一方法是,如果我手动更改resultset.getString(),但只会显示1个完整行。

    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("test");

  stmt = con->createStatement();
  res = stmt->executeQuery("SELECT 'Hello World!' AS _message");
  while (res->next()) {
    cout << "\t... MySQL replies: ";
    /* Access column data by alias or column name */
    cout << res->getString("_message") << endl;
    cout << "\t... MySQL says it again: ";
    /* Access column fata by numeric offset, 1 is the first column */
    cout << res->getString(1) << endl;
  }

正如您在第二行最后一行所见“cout&lt;&lt; res-&gt; getString(1)&lt;&lt; endl;”他们手动选择第一列。

是否可以选择所有列,以便输出所有列中的所有行?

1 个答案:

答案 0 :(得分:2)

修改

最后,这将为您提供所需的......

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

int main(int argc, const char *argv[]) {

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

  /* Connect to the MySQL so_test database */
  con->setSchema("so_test");
  stmt = con->createStatement();

  // Select all columns/rows from example_table
  res = stmt->executeQuery("SELECT * FROM example_table");

  //get result set metadata
  sql::ResultSetMetaData *res_meta = res -> getMetaData();
  int columns = res_meta -> getColumnCount();

  //Loop for each row
  while (res->next()) {
    /* Access column data by index, 1-indexed*/
    for (int i = 1; i <= columns; i++) {
      cout << res->getString(i) << "|" ;
    }
    cout << endl;
  }

  return 0;
}

不要忘记包括

#include <resultset_metadata.h>