gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:39:23 34 4
gpt4 key购买 nike

我正在尝试使用 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/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com