「RustによるWebアプリケーション開発(豊田優貴著)」を読むと、axumのルーティングでwith_state(conn_pool)で接続情報を持たせてますね。まぁそういう方法もありかと思いますが、今回は、関数で呼び出す方法を採用することにした。
参考のソースコード:
https://github.com/kingluo/tokio-postgres-hello-world/blob/master/src/main.rs
async fn psql_connect() -> Result<Client, Box<dyn std::error::Error>> { let (client, connection) = tokio_postgres::connect("host=localhost user=postgres password=hogehoge", NoTls).await?; tokio::spawn(async move { if let Err(e) = connection.await { eprintln!("connection error: {}", e); } }); Ok(client) } async fn check_users()-> Result<(), Box<dyn std::error::Error>> { let client = psql_connect().await.unwrap(); for row in client.query("SELECT id, username, password From users", &[]).await? { let id: i32 = row.get(0); let name: String = row.get(1); let password: String = row.get(2); println!("{} {} {}", id, name, password); } Ok(()) }