MySQL C++连接器:参数的符号名称

MySQL C++ connector: symbolic names for parameters?

本文关键字:符号 参数 C++ 连接器 MySQL      更新时间:2023-10-16

我需要MySQL查询参数的符号名称,因为查询在其WHERE子句中使用了一个非常复杂的表达式。遗憾的是,C++连接器不支持命名参数。我有一个想法,使用两个语句,一个设置变量,另一个使用它们,如下所示:

const char* req =
    " SET @id=?, @from=?, @to=?;"
    " SELECT ..., creation_date, ... "
    " FROM ... "
    " WHERE ... AND (@from is null OR @from is not null AND creation_date >= @from) AND (@to is null OR @to is not null AND creation_date <= @to)";
// in practice, the WHERE condition is even more complex than the above
std::unique_ptr<sql::PreparedStatement>stmt(con->prepareStatement(req));
....

但这不起作用,连接器无法执行多个语句。

此外,从我读到的内容来看,不清楚在第一条语句完成后变量是否仍然存在。

如何在查询中使用符号名称?

我不会接受自己的答案,希望有人想出更好的解决方案。

穷人的符号变量是通过字符串替换来实现的:

const char* req_cstr =
    " SET @id=?, @from=?, @to=?;"
    " SELECT ..., creation_date, ... "
    " FROM ... "
    " WHERE ... AND (@from is null OR @from is not null AND creation_date >= @from) AND (@to is null OR @to is not null AND creation_date <= @to)";
std::string req(req_cstr);
std::string to = std::to_string(timeTo) + " ";
replaceAll(req,"@to",to);
//replaceAll(req,"@from",...);

然后执行修改后的请求。

您必须注意SQL变量名称,很容易将它们与C++变量名称混淆,例如replaceAll(req,"@after",after);上述查询是错误的,因为变量称为"@from"

替换所有函数是(原点):

void replaceAll(std::string& str, const std::string& from, const std::string& to) {
    if(from.empty())
    return;
    size_t start_pos = 0;
    while((start_pos = str.find(from, start_pos)) != std::string::npos) {
    str.replace(start_pos, from.length(), to);
    start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
    }
}