向const char *传递参数构建MySQL查询时出现编译错误求助
解决C++拼接MySQL LIKE查询字符串的编译错误
错误原因
你遇到的编译错误,本质是C++里字符串字面量(const char[])和const char*不能直接用+运算符做字符串拼接。代码里的"select name from authors where name like '%'"是const char[]类型,author是const char*指针,两者相加会被编译器解析成指针算术(地址偏移),而非字符串拼接;后续再加上"'%"时,编译器找不到匹配的运算符,就会抛出expression must have integral or unscoped enum type错误。
解决方案1:用std::string完成字符串拼接
C++的std::string重载了+运算符,支持直接和字符串字面量、其他std::string拼接,是最直接的修复方式:
std::string author_str = getString("Author: ", 100); std::string query = "select name from authors where name like '%" + author_str + "%'"; res = exec_query(conn, query.c_str());
先把用户输入转成std::string,再拼接成完整的查询语句,最后用c_str()转成const char*传给exec_query即可。
解决方案2:使用预处理语句(推荐,避免SQL注入)
直接拼接字符串存在严重的SQL注入风险(比如用户输入' OR 1=1 --会返回所有数据),更安全的做法是用MySQL的预处理语句,通过参数绑定实现查询:
std::string author_str = getString("Author: ", 100); MYSQL_STMT* stmt = mysql_stmt_init(conn); if (!stmt) { // 处理预处理语句初始化错误 } // 用concat函数拼接%和参数,避免手动处理字符串 const char* query = "select name from authors where name like concat('%', ?, '%')"; if (mysql_stmt_prepare(stmt, query, strlen(query)) != 0) { // 处理预处理错误 } // 绑定参数 MYSQL_BIND param; memset(¶m, 0, sizeof(param)); param.buffer_type = MYSQL_TYPE_STRING; param.buffer = (char*)author_str.c_str(); param.buffer_length = author_str.length(); if (mysql_stmt_bind_param(stmt, ¶m) != 0) { // 处理参数绑定错误 } if (mysql_stmt_execute(stmt) != 0) { // 处理执行错误 } res = mysql_stmt_result_metadata(stmt); // 后续处理结果集逻辑... mysql_stmt_close(stmt);
这种方式不仅避免了字符串拼接的编译问题,还从根源上杜绝了SQL注入风险,生产环境中优先推荐使用。
内容的提问来源于stack exchange,提问作者kluzix
相关产品推荐
相关产品推荐

