# Connection DataBase

**URL:** <https://users.rust-lang.org/t/connection-database/52195>\
**Category:** uncategorized\
**Created:** [December 2, 2020, 4:22am UTC](https://users.rust-lang.org/t/connection-database/52195 "2020-12-02T04:22:25Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![benjamin123](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/benjamin123/32/17810_2.png) [@benjamin123](https://users.rust-lang.org/u/benjamin123)\
**Post date:** [December 2, 2020, 4:22am UTC](https://users.rust-lang.org/t/connection-database/52195/1 "2020-12-02T04:22:26Z")

</div>

I am using actix-web,  
In the main the connection of the DB is defined and the reference is passed

```rust
  let mut server = HttpServer::new(move || {
        App::new()
            .data(db_pool.clone()) // pass database pool to application so we can access it inside handlers
            .route("/", web::get().to(index))
            .configure(todo::init) // init todo routes
    });

```

In another controller the connection is passed by reference `db_pool: web::Data<PgPool>`

```rust
async fn find_all(db_pool: web::Data<PgPool>) -> impl Responder {
    let result = Todo::find_all(db_pool.get_ref()).await;
    match result {
        Ok(todos) => HttpResponse::Ok().json(todos),
        _ => HttpResponse::BadRequest().body("Error trying to read all todos from database")
    }
}

```

If I invoke the connection directly in the method, would it be optimal? , or would I be invoking the DB many times and it would not be optimal?  
Example

```rust
async fn find_all() -> impl Responder {
   let db_pool = sqlx_test::new::<PgPool>().await?;
    let result = Todo::find_all(db_pool.get_ref()).await;
    match result {
        Ok(todos) => HttpResponse::Ok().json(todos),
        _ => HttpResponse::BadRequest().body("Error trying to read all todos from database")
    }
}

```

---

<div class="post-metadata">

**Author:** ![alice](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/alice/32/9777_2.png) [@alice](https://users.rust-lang.org/u/alice)\
**Post date:** [December 2, 2020, 5:01pm UTC](https://users.rust-lang.org/t/connection-database/52195/2 "2020-12-02T17:01:39Z")

</div>

You should not create a new pool inside `find_all`. Then database connections would not be reused.

---

<div class="post-metadata">

**Author:** ![system](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/system/32/51372_2.png) [@system](https://users.rust-lang.org/u/system)\
**Post date:** [March 2, 2021, 5:01pm UTC](https://users.rust-lang.org/t/connection-database/52195/3 "2021-03-02T17:01:42Z")

</div>

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.
