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

使用Rust的ODBC-API crate连接SQL Server时遇get_col方法不存在错误

问题

我正尝试使用Rust语言,借助warp crate构建REST API,并通过ODBC-API crate连接MS SQL Server,但遇到了编译错误。

我的代码如下:

use odbc_api::{ConnectionOptions, Environment, Cursor};
use serde::Serialize;
use warp::{Filter, Rejection, Reply};

#[derive(Serialize)]
struct Data {
    name: String,
    price: f64,
    quantity: i32,
}

async fn fetch_data() -> Result<Vec<Data>, odbc_api::Error> {
    let env = Environment::new()?;
    let connection_string = "Driver={ODBC Driver 17 for SQL Server};Server=Connection_String ..."; // Connection details
    let mut conn = env.connect_with_connection_string(connection_string, ConnectionOptions::default())?;
    let sql = "SELECT name, price, quantity \
    FROM dbo.tblGrocery
    WHERE status = 1
    ORDER BY name ASC"; // SQL query
    let cursor = conn.execute(sql, ())?;
    let mut data = Vec::new();
    if let Some(cursor) = cursor {
        while let Some(row) = cursor.next_row()? {
            let name: String = row.get_col(1)?;
            let price: f64 = row.get_col(2)?;
            let quantity: i32 = row.get_col(3)?;
            data.push(Data { name, price, quantity });
        }
    }
    Ok(data)
}

async fn handle_request() -> Result<impl Reply, Rejection> {
    let data = fetch_data().await.unwrap();
    Ok(warp::reply::json(&data))
}

#[tokio::main]
async fn main() {
    let route = warp::get().and(warp::path("data")).and_then(handle_request);
    warp::serve(route).run(([127, 0, 0, 1], 3030)).await;
}

编译错误信息:

error[E0599]: no method named `get_col` found for struct `CursorRow` in the current scope
  --> src\main.rs:24:36
   |
24 |             let name: String = row.get_col(1)?;
   |                                    ^^^^^^^ method not found in `CursorRow<'_>`      

error[E0599]: no method named `get_col` found for struct `CursorRow` in the current scope
  --> src\main.rs:25:34
   |
25 |             let price: f64 = row.get_col(2)?;
   |                                  ^^^^^^^ method not found in `CursorRow<'_>`

error[E0599]: no method named `get_col` found for struct `CursorRow` in the current scope
  --> src\main.rs:26:37
   |
26 |             let quantity: i32 = row.get_col(3)?;
   |                                     ^^^^^^^ method not found in `CursorRow<'_>`

Cargo.toml配置:

[package]
name = "neat-api"
version = "0.1.0"
edition = "2021"

[dependencies]
odbc-api = "0.57.0"
warp = "0.2"
serde = { version = "1.0", features = ["derive"] }

解决方案

错误根源是**CursorRow类型没有get_col方法**,在odbc-api 0.57.0版本中,获取列数据的正确方法是get,而且列索引从0开始计数(不是你代码里的1)。

修改后的fetch_data函数代码:

async fn fetch_data() -> Result<Vec<Data>, odbc_api::Error> {
    let env = Environment::new()?;
    let connection_string = "Driver={ODBC Driver 17 for SQL Server};Server=Connection_String ..."; // Connection details
    let mut conn = env.connect_with_connection_string(connection_string, ConnectionOptions::default())?;
    let sql = "SELECT name, price, quantity \
    FROM dbo.tblGrocery
    WHERE status = 1
    ORDER BY name ASC"; // SQL query
    let cursor = conn.execute(sql, ())?;
    let mut data = Vec::new();
    if let Some(mut cursor) = cursor {
        while let Some(row) = cursor.next_row()? {
            let name: String = row.get(0)?;
            let price: f64 = row.get(1)?;
            let quantity: i32 = row.get(2)?;
            data.push(Data { name, price, quantity });
        }
    }
    Ok(data)
}

核心修改点:

  • 把row.get_col(n)替换为row.get(n-1),因为列索引从0开始
  • 给cursor变量添加mut修饰符,因为next_row需要可变引用

额外优化建议:不要在handle_request中用unwrap(),避免程序因数据库错误直接panic,改用错误映射处理:

async fn handle_request() -> Result<impl Reply, Rejection> {
    fetch_data().await
        .map(|data| warp::reply::json(&data))
        .map_err(|e| warp::reject::custom(e))
}

(需要确保odbc_api::Error实现了Reject trait,或者自定义一个适配warp的错误类型)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 11:17:52