You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MySQL C++获取行数据转字符串异常:返回数值而非文本求助

问题解决:Telegram机器人从MySQL取字符串数据并发送

问题根源

  1. 你的get_topics函数返回类型是char,return *row[1]只会返回row[1]字符串的第一个字符的ASCII数值,用to_string转换后自然变成数字。
  2. while循环第一次迭代就直接return,只能拿到数据库第一行数据,无法返回所有内容。

正确实现代码

1. 修改get_topics函数,返回完整字符串

将返回类型改为std::string,拼接所有查询到的数据:

#include <string> // 确保包含这个头文件

std::string MainBot::get_topics(char lvl) {
    std::string result_text;

    if(lvl == 'j') {
        res = mysql_perform_query(con, "select * from Topics;");
        if (!res) {
            return "数据库查询失败";
        }

        while ((row = mysql_fetch_row(res)) != NULL) {
            // 每一行数据之间加空行分隔,格式可自定义
            if (!result_text.empty()) {
                result_text += "\n\n";
            }
            // 拼接各列内容,row是char**,直接转std::string即可
            result_text += "ID: " + std::string(row[0]) + "\n";
            result_text += "通用问题: " + std::string(row[1]) + "\n";
            result_text += "编译相关: " + std::string(row[2]) + "\n";
            result_text += "C++与OOP: " + std::string(row[3]) + "\n";
            result_text += "STL算法: " + std::string(row[4]) + "\n";
            result_text += "Linux系统: " + std::string(row[5]) + "\n";
        }

        mysql_free_result(res); // 释放结果集,避免内存泄漏
    }

    return result_text.empty() ? "未找到对应数据" : result_text;
}

2. 调整回调中的调用逻辑

不需要用to_string,直接传递返回的字符串:

bot.getEvents().onCallbackQuery([this,&bot](const CallbackQuery::Ptr& query) {
    if (query->data == "Junior") {
       std::string content = get_topics('j');
       bot.getApi().sendMessage(query->message->chat->id, content);
    }
});

额外注意事项

  • 确保代码中包含<string>头文件,否则std::string会报错。
  • 每次查询结束后必须调用mysql_free_result(res)释放内存,避免内存泄漏。
  • 可以根据需求调整字符串拼接的格式,比如用分隔线替代空行,或者只返回指定列的数据。

内容的提问来源于stack exchange,提问作者ShellCpp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 08:40:34