gpt4 book ai didi

c++ - MySQL C++ 连接器 : symbolic names for parameters?

转载 作者:行者123 更新时间:2023-11-29 21:36:36 25 4
gpt4 key购买 nike

我需要 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"

replaceAll 函数为 ( origin ):

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'
}
}

关于c++ - MySQL C++ 连接器 : symbolic names for parameters?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34878904/

25 4 0