在网上广泛搜索后,我仍然没有找到解决这个问题的方法。
我正在编写一个连接到在线数据库并在列表框中输出数据的小型 C++ 应用程序。
我需要使用编辑框启用搜索功能,但在使用变量时无法使查询正常工作。
我的代码是:
res = mysql_perform_query (conn, "select distinct artist from Artists");
//res = mysql_perform_query (conn, "select album from Artists where artist = ' ' ");
while((row = mysql_fetch_row(res)) != NULL){
CString str;
UpdateData();
str = ("%s\n", row[0]);
UpdateData(FALSE);
m_list_control.AddString(str);
}
第一行“res =
”工作正常,但我需要第二行才能工作。我为编辑框设置了一个成员变量 m_search_edit
,但我尝试将其包含在 sql 语句中的任何方式都会导致错误。
例如。
res = mysql_perform_query (conn, "select album from Artists where artist = '"+m_search_edit+" ' ");
导致此错误:
error C2664: 'mysql_perform_query' : cannot convert parameter 2 from 'class CString' to 'char *' No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called"
当我将 m_search_edit
转换为 char*
时,出现“无法添加 2 个指针”错误。
有什么办法解决这个问题吗?
最佳答案
这里的问题是您可能正在为 Unicode 构建,这意味着 CString 由宽字符组成。您不能直接将 ASCII 字符串与宽字符串连接起来(也不能将字符串文字与 + 运算符连接起来)。
我认为在这里构建查询字符串的最清晰的方法是使用 CT2CA
宏将编辑控件的内容从 Unicode 转换为 ASCII 和 CStringA::Format
将它们插入到字符串中
CStringA query;
query.Format("select album from Artists where artist = '%s'", CT2CA(m_search_edit));
res = mysql_perform_query(conn, query);
正如 Thomas 所指出的,您应该意识到这为 SQL 注入(inject)敞开了大门...
编辑:我不确定这个 mysql_perform_query
API 是从哪里来的,但是从您发布的错误消息来看,它看起来还需要一个可写缓冲区(char *
而不是 const char *
)。由于我找不到它的文档,我不知道它期望缓冲区有多大,但是要从 CString 中获取可修改的缓冲区,请查看 GetBuffer()和 ReleaseBuffer()方法:
CStringA query;
query.Format(...); // Replace ... with parameters from above
char * buffer = query.GetBuffer(MAX_STRING_LENGTH); // make length big enough for mysql
res = mysql_perform_query(conn, buffer)
query.ReleaseBuffer();
EDIT2(回应最新评论):
感谢您提供 mysql_perform_query
函数的定义。以后提问时,请记住了解您何时创建了像这样的辅助函数会很有帮助。
在这种情况下,您的 mysql_perform_query
函数永远不会修改查询字符串——它唯一做的就是将它传递给 mysql_query
,它接受一个 const char *
,所以你没有理由不声明它的参数const
。一旦你这样做了,你会发现我的第一个答案有效(不需要 GetBuffer/ReleaseBuffer):
MYSQL_RES *mysql_perform_query(MYSQL *conn, const char * query)
{
// Body as written in comment.
}
关于c++ - 在 C++ MFC 程序中的 mysql 查询中使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2709699/