使用Nanodbc在同一SQL查询中获取不同数据类型报错求助
Nanodbc混合类型查询出现「Invalid Descriptor Index」错误的解决办法
这个错误不是因为同时查询字符串和数值类型字段导致的,核心原因是ODBC驱动处理结果集描述符时的兼容性问题,或是字段类型与读取方式不匹配引发的索引偏移。
可能的触发原因
- 数据库中
Odds字段的实际类型(比如decimal/numeric)与你用double直接读取的类型不兼容,驱动在转换时出现描述符索引错误。 - 混合类型结果集的情况下,ODBC驱动对结果集的字段索引定位出现偏移,导致
get<T>方法找不到对应位置的字段。
解决方法
SQL层面显式转换字段类型
将Odds字段转换为驱动兼容的浮点类型,避免类型映射冲突:Select horseName, Meet, CAST(Odds AS FLOAT) from Racing_RacesTrixie通过字段名而非索引读取数据
放弃索引定位,改用字段名读取,彻底避免索引偏移问题:std::string horsename = result.get<std::string>("horseName"); std::string meet = result.get<std::string>("Meet"); double odds = result.get<double>("Odds");更新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
相关产品推荐
相关产品推荐

