arysev
1
I use actix and tokio_postgres lib
How i can get several users from table and serialize them?
Now i can get only one user
#[get("/")]
pub async fn user_list(db_pool: web::Data<Pool>) -> Result<HttpResponse, Error> {
let client: Client = db_pool
.get()
.await
.map_err(custom::CustomError::PoolError)?;
let rows = client.query("select * from users", &[]).await.unwrap();
let user = User {
email: rows[0].get(1),
login: rows[0].get(2),
};
return Ok(HttpResponse::Ok().json(user));
}
ZiCog
2
In your code rows
is an array. So you need to loop over all the elements of that array (kids to day like to say `iterate').
I have toyed with such an example when starting out with the Rocket web server. It looks like this:
#[derive(Serialize)]
struct Person {
id: i64,
name: String,
data: Option<Vec<u8>>,
}
#[derive(Serialize)]
struct Persons {
persons: Vec<Person>,
}
#[get("/public/api/persons")]
fn api_persons(model: State<Model>) -> Json<Persons> {
let mut conn = model.connect();
let rows = conn
.query("SELECT id, name, data FROM person", &[])
.unwrap();
let mut results = Persons { persons: vec![] };
for row in &rows {
let person = Person {
id: row.get(0),
name: row.get(1),
data: row.get(2),
};
results.persons.push(person);
}
Json(results)
}
ZiCog
3
What I wantto know is how you made that tokio-postgres database connection pool?
system
Closed
4
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.