Im trying to use sqlx to get data from a mysql db. I have the following:
#[derive(Debug, PartialEq, Eq, sqlx::FromRow)]
struct Room {
name: String
}
let mut stream = sqlx::query_as::<_, Room>(r#"SELECT name FROM rooms"#)
.fetch_all(&db.pool).await;
for row in stream {
println!("{:?}",row);
}
So in stream there is a vector and each index seems to hold the actual query results. So
stream[0] = [Room{name: "Room 1"}, Room{name: "Room 3"}, Room{name: "Room 2"}]
So in order to get at that data i have to loop through stream[0]. Is there a way to have that data on the value returned from the query without the explicit index?
Use Query::fetch() (this will return a stream of results, fetching the next one as needed) instead of Query::fetch_all() (this will return a vec of all results, fetching them all before hand), and then loop over the result stream.
Like so:
let mut stream = sqlx::query_as::<_, Room>(r#"SELECT name FROM rooms"#)
.fetch(&db.pool);
stream.for_each(|room| println!("{:#?}", room));
Alternatively, you can use a while loop to print, but you may need to Pin your stream before calling next().
while let Some(room) = stream.next().await {
println! ("{:#?}", room);
}
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