在 Rust 中使用 ODBC Crate 连接到 SQL Server 时出错

问题描述 投票:0回答:1

有人知道如何解决这个问题吗?尝试使用 Rust 制作 REST API(用于 API 的 warp crate 和连接到 MS SQL Server 的 ODBC-API Crate)。

代码:

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"] }
rust odbc warp
1个回答
0
投票

get_col
方法不存在。您可以使用
get_text
代替。请参阅https://docs.rs/odbc-api/3.0.1/odbc_api/struct.CursorRow.html#method.get_text

© www.soinside.com 2019 - 2024. All rights reserved.