我需要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));
....
但这不起作用,连接器无法执行多个语句。
此外,根据我的阅读,目前尚不清楚在第一个陈述完成后变量是否仍然存在。
如何在查询中使用符号名称?
答案 0 :(得分:0)
我不会接受我自己的答案,希望有人能提出更好的解决方案。
穷人的符号变量是通过字符串替换实现的:
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'
}
}