运行任意 SQL 命令 MySQL C++ (X DevAPI)?

问题描述

我已将我的 C++ 项目连接到 MysqL 并成功创建了一个会话。我能够创建一个架构。我的问题是,当我尝试使用 MysqL/C++ api 运行简单的任意查询(如 USE testSchema SHOW tables;)时,我遇到了 sql 语法错误。当我直接在 MysqL shell 中运行该函数时,查询运行得非常好。

这是完整的代码

const char* url = (argc > 1 ? argv[1] : "MysqLx://pct@127.0.0.1");
cout << "Creating session on " << url << " ..." << endl;

Session sess(url);

{
    cout << "Connected!" << endl;

    // Create the Schema "testSchema"; This code creates a schema without issue
    cout << "Creating Schema..." << endl;
    sess.dropSchema("testSchema");
    Schema mySchema = sess.createSchema("testSchema");
    cout << "Schema Created!" << endl;


    // Create the Table "testTable"; This code runs like normal,but the schema doesn't show
    cout << "Creating Table with..." << endl;
    sqlStatement sqlcomm = sess.sql("USE testSchema SHOW tables;");
    sqlcomm.execute();
}

这是控制台输出

Creating session on MysqLx://pct@127.0.0.1 ...
Connected!
Creating Schema...
Schema Created!
Creating Table with...
MysqL ERROR: CDK Error: You have an error in your sql Syntax; check the manual that corresponds to your MysqL server version for the right Syntax to use near 'SHOW tables' at line 1

错误 You have an error in your sql Syntax; check the manual that corresponds to your MysqL server version for the right Syntax to use near 'SHOW tables' at line 1MysqL 错误,这意味着我在查询中有语法错误,但是当我仔细查看查询时,我发现它没有任何问题。

我已经将代码直接从 cpp 文件复制并粘贴到 MysqL shell 中,它运行完美。这告诉我我在 sql() 函数中输入查询的格式有问题。但是 sql() 函数的文档非常简洁。

这里是对 sql() 函数的引用:https://dev.mysql.com/doc/dev/connector-cpp/8.0/class_session.html#a2e625b5223acd2a3cbc5c02d653a1426

有人能告诉我我哪里出错了吗?还有这里是更多上下文的完整 cpp 代码https://pastebin.com/3kQY8THC

Windows 10 视觉工作室 2019 MysqL 8.0 与 Connect/C++ X DevAPI

解决方法

您可以分两步完成:

sess.sql("USE testSchema").execute();

SqlStatement sqlcomm = sess.sql("SHOW tables");
SqlResult res = sqlcomm.execute();
for(auto row : res)
{
   std::cout << row.get(0).get<std::string>() << std::endl;
}

此外,您可以使用 Schema::getTables():

for(auto table : mySchema.getTables())
{
  std::cout << table.getName() << std::endl;
}

请记住,Schema::getTables() 不显示由 Schema::createCollection() 创建的集合。还有一个Schema::getCollections()

for(auto collection : mySchema.getCollections())
{
  std::cout << collection.getName() << std::endl;
}