如何在Rust中将SQLX记录加载到结构体的Vec中

4
我有一个名为“instruments”的表,其中包含以下字段:
  • id,
  • instrument_token(整数)
  • tradingsymbol(可空的字符串字段)
我已经定义了一个 Rust 结构体如下:
pub struct Instrument {
    pub id: i64,
    pub instrument_token: i32,
    pub tradingsymbol: Option<String>,
}

我使用SQLX在一个函数内查询并创建了Vec<Instrument>,实现方法如下:

     let records = sqlx::query!(r"select * from instruments").fetch_all(&app_context.db_connection).await?;


        let mut all_instruments: Vec<Instrument> = Vec::new();
        for rec in records {
            all_instruments.push(Instrument {
                id: rec.id,
                instrument_token: rec.instrument_token,
                tradingsymbol: rec.tradingsymbol,
            });
        }

这里的&app_context.db_connection&pool实例。

有没有更好的方法使用SQLX将记录加载到结构体中呢?如果有,应该怎么做?

1个回答

4
如果您的记录和数据类型具有相同的字段名称和类型,则可以使用 query_as! 进行替代:
let records: Vec<Instrument> =
    sqlx::query_as!(Instrument, r"select * from instruments")
        .fetch_all(&app_context.db_connection)
        .await?;

在结构体和数据库中,所有字段都必须完全匹配,还是我可以挑选想要使用的字段? - Asnim P Ansari
1
@AsnimPAnsari 我认为你查询中的所有列都必须与类型的字段匹配。不过,你可以编写查询以仅选择特定列。 - Frxstrem

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接