在向量Rust中获取tiberius select查询的每一行:寿命误差

58wvjzkj  于 2023-03-23  发布在  其他
关注(0)|答案(1)|浏览(165)

我用tiberius连接到一个mssql数据库,我把所有需要的数据放到一个结构体中,每个结构体都放到一个vec中,我希望我的函数返回我的vec,但我不明白这个借用问题。
cannot return value referencing local variable row返回引用当前函数拥有的数据的值
mod.rs(32 ,15):row在此借用
这是我的职责

use tiberius::{Client, Config, AuthMethod, Query, Row};
use tokio::net::TcpStream;
use tokio_util::compat::TokioAsyncWriteCompatExt;
pub mod structures;
use structures::*;

#[tokio::main]
pub async fn get_fornitori() -> anyhow::Result<Vec<Fornitori<'static>>> {
    let mut config = Config::new();

    config.host("foo");
    config.port(1433);
    config.authentication(AuthMethod::sql_server("foo", "bar"));
    config.database("foo");
    config.trust_cert(); // on production, it is not a good idea to do this

    let tcp = TcpStream::connect(config.get_addr()).await?;
    tcp.set_nodelay(true)?;

    let mut client = Client::connect(config, tcp.compat_write()).await?;
    let params = vec![String::from("*")];
    let mut select = Query::new("SELECT TOP 3 * FROM foo");
    
    for param in params.into_iter() {
        select.bind(param);
    }
    
    let mut _res = select.query(&mut client).await?;
    let row: Vec<Vec<Row>> = _res.into_results().await?;

    let mut result_vec: Vec<Fornitori> = vec![];
    for i in &row[0] {
        let id_forn: Option<i32> = i.get(0);
        let nome_forn: Option<&str> = i.get(1);
        let pagamento_forn: Option<&str> = i.get(4);
        let forn = Fornitori {
            f_id: id_forn,
            fornitore: nome_forn,
            tipo_pagamento: pagamento_forn,
        };
        result_vec.push(forn);
    }
    println!("rvec: {:#?}", result_vec);

    Ok(result_vec)
}

我在这里得到错误:
OK(result_vec)
我在另一个文件中有Fornitori结构

#[derive(Clone, Debug)]
pub struct Fornitori<'a> {
    pub f_id: Option<i32>,
    pub fornitore: Option<&'a str>,
    pub tipo_pagamento: Option<&'a str>,
}

我用“foo”和“bar”替换真实的。

dxxyhpgq

dxxyhpgq1#

因为你正在创建新的Fornitori项,所以它应该拥有它的字段:

#[derive(Clone, Debug)]
pub struct Fornitori {
    pub f_id: Option<i32>,
    pub fornitore: Option<String>,
    pub tipo_pagamento: Option<String>,
}

您可以简单地从ToString::to_stringMap得到的字符串切片创建新的sting:

for i in &row[0] {
        let f_id = i.get(0);
        let fornitore = i.get(1).map(|f: &str| f.to_string());
        let tipo_pagamento = i.get(4).map(|t: &str| t.to_string());
        let forn = Fornitori {
            f_id,
            fornitore,
            tipo_pagamento,
        };
        result_vec.push(forn);
    }

相关问题