postgresql - 错误 : failed to connect to database: password authentication failed in Rust

标签 postgresql rust rust-sqlx

我正在尝试使用 sqlx crate 和 Postgres 数据库连接到 Rust 中的数据库。

main.rs:

use dotenv;
use sqlx::Pool;
use sqlx::PgPool;
use sqlx::query;

#[async_std::main]
async fn main() -> Result<(), Error> {
    dotenv::dotenv().ok();
    pretty_env_logger::init();
    let url = std::env::var("DATABASE_URL").unwrap();
    dbg!(url);

    let db_url = std::env::var("DATABASE_URL")?;
    let db_pool: PgPool = Pool::new(&db_url).await?;

    let rows = query!("select 1 as one").fetch_one(&db_pool).await?;
    dbg!(rows);

    let mut app = tide::new();
    app.at("/").get(|_| async move {Ok("Hello Rustacean!")});
    app.listen("127.0.0.1:8080").await?;

    Ok(())
}

#[derive(thiserror::Error, Debug)]
enum Error {
    #[error(transparent)]
    DbError(#[from] sqlx::Error),

    #[error(transparent)]
    IoError(#[from] std::io::Error),

    #[error(transparent)]
    VarError(#[from] std::env::VarError),
}

这是我的.env 文件:

DATABASE_URL=postgres://localhost/twitter
RUST_LOG=trace

错误日志:

error: failed to connect to database: password authentication failed for user "ayman"
  --> src/main.rs:19:16
   |
19 |     let rows = query!("select 1 as one").fetch_one(&db_pool).await?;
   |                ^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)

error: aborting due to previous error

error: could not compile `backend`.

注意:

  1. 存在一个名为 twitter 的数据库。
  2. 我已经为 sqlx 的依赖包含了
sqlx = {version="0.3.5", features = ["runtime-async-std", "macros", "chrono", "json", "postgres", "uuid"]}

我是否缺少连接到数据库的某种级别的身份验证?我在 sqlx::Query 的文档中找不到它 macro

最佳答案

无法认证的原因是访问数据库前必须提供凭证

有两种方法可以做到这一点

选项 1:更改您的 URL 以包含凭据 - 例如 -

DATABASE_URL=postgres://localhost?dbname=mydb&user=postgres&password=postgres

选项 2 使用 PgConnectionOptions - 例如

let pool_options = PgConnectOptions::new()
        .host("localhost")
        .port(5432)
        .username("dbuser")
        .database("dbtest")
        .password("dbpassword");

    let pool: PgPool = Pool::<Postgres>::connect_with(pool_options).await?;

注意:我使用的sqlx版本是sqlx = {version="0.5.1"}

有关更多信息,请参阅文档 - https://docs.rs/sqlx/0.5.1/sqlx/postgres/struct.PgConnectOptions.html#method.password

希望对你有帮助。

关于postgresql - 错误 : failed to connect to database: password authentication failed in Rust,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63537490/

相关文章:

ruby-on-rails - 在 Terminal Rails 4 Postgresql 中将用户添加到用户表

rust - 如何在 3 中安装 Rust crate?

sql - 从 "has one through"关系中查找最近的记录

sql - 是否有 PostgreSQL 等同于 Oracle 的分析?

rust - 即使借用不可变的东西也有可能移动吗?

concurrency - 克隆 tokio channel 发件人以关闭 future 的替代方法

rust - 如何在 rocket.rs 中使 postgres 池连接全局化并使 FromRequest 自定义守卫异步?

rust - sqlx安装由于类型不匹配而失败

postgresql - 来自另一个容器内部的 Docker 端口不匹配