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

使用Nanodbc在同一SQL查询中获取不同数据类型报错求助

Nanodbc混合类型查询出现「Invalid Descriptor Index」错误的解决办法

这个错误不是因为同时查询字符串和数值类型字段导致的,核心原因是ODBC驱动处理结果集描述符时的兼容性问题,或是字段类型与读取方式不匹配引发的索引偏移。

可能的触发原因

  • 数据库中Odds字段的实际类型(比如decimal/numeric)与你用double直接读取的类型不兼容,驱动在转换时出现描述符索引错误。
  • 混合类型结果集的情况下,ODBC驱动对结果集的字段索引定位出现偏移,导致get<T>方法找不到对应位置的字段。

解决方法

  1. SQL层面显式转换字段类型
    将Odds字段转换为驱动兼容的浮点类型,避免类型映射冲突:

    Select horseName, Meet, CAST(Odds AS FLOAT) from Racing_RacesTrixie
    
  2. 通过字段名而非索引读取数据
    放弃索引定位,改用字段名读取,彻底避免索引偏移问题:

    std::string horsename = result.get<std::string>("horseName");
    std::string meet = result.get<std::string>("Meet");
    double odds = result.get<double>("Odds");
    
  3. 更新ODBC驱动版本
    确保使用的ODBC Driver 18 for SQL Server是最新版本,修复已知的驱动兼容性bug。

修正后的完整代码示例

nanodbc::connection& conn = DatabaseManager::getInstance().getConnection();
try {
    std::string query = "Select horseName, Meet, CAST(Odds AS FLOAT) from Racing_RacesTrixie";
    nanodbc::result result = nanodbc::execute(conn, query);

    while (result.next()) {
        std::string horsename = result.get<std::string>("horseName");
        std::string meet = result.get<std::string>("Meet");
        double odds = result.get<double>("Odds");
        // 这里可以添加数据处理逻辑
    }
}
catch (const nanodbc::database_error& e) {
    std::wcerr << L"Database error: " << e.what() << "\n";
}
catch (const std::exception& e) {
    std::cerr << "Exception: " << e.what() << "\n";
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 10:52:42