我有一个名为“instruments”的表,其中包含以下字段:
id
,instrument_token
(整数)tradingsymbol
(可空的字符串字段)
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将记录加载到结构体中呢?如果有,应该怎么做?