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

如何在Rust的Warp REST API中接入SQL Server?

Rust + Warp 替换本地存储为SQL Server遇到的问题

我是Rust新手,已使用Warp框架创建了一个REST API,参考LogRocket博客教程实现了基于本地存储的杂货清单接口。现在希望将本地存储替换为SQL Server,但操作后遇到了问题。

现有代码

use warp::{http, Filter};
use parking_lot::RwLock;
use std::collections::HashMap;
use std::sync::Arc;
use serde::{Serialize, Deserialize};
use sqlx::mssql::{Mssql, MssqlPoolOptions};
use sqlx::Row; // Import Row trait for working with query results

// Other functions 

#[tokio::main]
async fn main() {
    // Initializing MS SQL Server database connection pool
    let db_pool = MssqlPoolOptions::new()
        .connect("my_connection_string")
        .await
        .unwrap();

    let store = Store::new(db_pool);
    let store_filter = warp::any().map(move || store.clone());

    let add_items = warp::post()
        .and(warp::path("v1"))
        .and(warp::path("groceries"))
        .and(warp::path::end())
        .and(post_json())
        .and(store_filter.clone())
        .and_then(update_grocery_list);

    let get_items = warp::get()
        .and(warp::path("v1"))
        .and(warp::path("groceries"))
        .and(warp::path::end())
        .and(store_filter.clone())
        .and_then(get_grocery_list);

    let delete_item = warp::delete()
        .and(warp::path("v1"))
        .and(warp::path("groceries"))
        .and(warp::path::end())
        .and(delete_json())
        .and(store_filter.clone())
        .and_then(delete_grocery_list_item);

    let update_item = warp::put()
        .and(warp::path("v1"))
        .and(warp::path("groceries"))
        .and(warp::path::end())
        .and(post_json())
        .and(store_filter.clone())
        .and_then(update_grocery_list);

    let routes = add_items.or(get_items).or(delete_item).or(update_item);

    // Add the cors middleware
    let cors = warp::cors()
        .allow_origin("http://localhost:3000")
        .allow_methods(vec!["GET", "POST", "PUT", "DELETE"]);

    // Apply the cors middleware to the routes
    let routes_with_cors = routes.with(cors);

    warp::serve(routes_with_cors)
        .run(([127, 0, 0, 1], 3030))
        .await;
}

Cargo.toml配置

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

[dependencies]
warp = "0.3"
parking_lot = "0.11"
serde = { version = "1.0", features = ["derive"] }
sqlx = { version = "0.5", features = ["runtime-tokio-native-tls", "macros"] }
sqlx-core = { version = "0.5", features = ["mssql"] }

错误情况

运行时出现多个错误,提示syn crate无法找到sqlx-macros crate中导入的特定模块、类型或宏。

求助需求

希望能得到问题解决方法,或者推荐关于Rust连接SQL Server的在线文章或YouTube视频。

内容的提问来源于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 19:39:53