MySQL C++连接器:参数的符号名称
MySQL C++ connector: symbolic names for parameters?
我需要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'
}
}
相关文章:
- 为函数定义符号不明确的指针参数
- Constexpr 可变参数模板,用于对无符号整数进行重新排序
- 引入参数化构造函数后显示 LNK 2019 未解析外部符号的代码错误
- C++如何将变量传递给带有无符号 int & 的参数uint16_t函数?
- 可变参数模板在目标文件中有重复的符号?
- 如何动态加载和调用具有特定于库的类型作为函数参数的符号
- 指针符号在参数规范中表示什么,例如:(char16 *缓冲区,int32 大小)?C++
- 如何定义具有依赖于符号调试的参数的函数
- 构造函数参数列表之后的结肠符号
- 是否可以确定函数的参数是否已签名或无符号,以实现可能性超载函数
- 模板参数可以既是 int 又可以是无符号长整型吗?
- 当功能采用签名的int时,将浮点参数施放为未符号
- 在与时间一起使用 srand 时,如果我没有time_t参数明确地将参数转换为无符号的 int 参数,这有关系吗?
- Variadic模板参数包只接受无符号int或size_t作为其类型
- 如果未设置编译符号,如何排除方法?如何传递可变数量的参数并在函数体中格式化它们
- 如何获得无符号的int作为控制台参数
- 当将负文字作为无符号参数传递时,可以g++警告
- 在 x86-64 平台上为 C(++) 中的 64 位无符号参数计算 (a*b)%n FAST
- 解释此并发中的"="符号参数::任务调用
- 如何将无符号参数传递给模板