I have a table named instruments with the following fields:
id,instrument_token (integer)tradingsymbol (nullable string field) I have defined a Rust struct as below
pub struct Instrument {
pub id: i64,
pub instrument_token: i32,
pub tradingsymbol: Option<String>,
}
I query and create a Vec<Instrument> inside a function as follows using SQLX
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,
});
}
Here &app_context.db_connection is &pool instance.
Is this there a better way to load records to a struct using SQLX. If yes how?
If your record and data type have the same field names and types, you can use query_as! instead:
let records: Vec<Instrument> =
sqlx::query_as!(Instrument, r"select * from instruments")
.fetch_all(&app_context.db_connection)
.await?;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With