Home > Net >  How to get value by field name in MYSQL xdevapi 8.0 connector c
How to get value by field name in MYSQL xdevapi 8.0 connector c

Time:02-25

For connector c 1.1, in this example, it's quite easy to get values by specifying the column name (or alias name).
But when I upgraded to version 8.0 xdevapi, I found this feature is no longer supported.

#include <mysqlx/xdevapi.h>

using namespace std;
using namespace mysqlx;

Session sess(<server_url>);
auto result = sess.sql("SELECT * FROM student").execute();
Row row = result.fetchOne();
cout << row[0] << endl;         // <- ok
cout << row["ID"] << endl;      // <- can compile but garbage output
cout << row.get("ID") << endl;  // <- cannot compile

I know the column names can be retrieved from result.getColumn(n).getColumnLabel(), but IMO it's useless. A "field" -> "index" mapping can really help the developers.

I'm new to C , so the following sentenses maybe too naive. Here's the possible ways I guess:

  • construct a STL map to record the mapping
  • iterate through the result.getColumns(), then check the getColumnLabel()
  • something like indexOf? But I find result.getColumns() does not support this method since it's a deque

CodePudding user response:

There is no way, at the moment, to get the column value using name.

A way is, as you suggest, a map with the name / index pair.

Something like this would work:

SqlResult sql_res = sess.sql("select * from table").execute();

std::map<std::string, size_t> columns;
auto fill_columns = [&sql_res, &columns]() -> void
{
  size_t idx = 0;
  for (auto &el : sql_res.getColumns())
  {
    columns.emplace(std::make_pair(el.getColumnLabel(), idx  ));
  }
};

fill_columns();

And then, using it:

for(auto row : sql_res)
{
  std::cout << "a:" << row[columns["a"]] << std::endl;
  std::cout << "b:" << row[columns["b"]] << std::endl;
}
  • Related