[英]Error: failed to connect to database: password authentication failed in Rust
I am trying to connect to database in Rust using sqlx
crate and Postgres database.我正在尝试使用sqlx
crate 和 Postgres 数据库连接到 Rust 中的数据库。
main.rs
: 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),
}
Here is my .env
file:这是我的.env
文件:
DATABASE_URL=postgres://localhost/twitter
RUST_LOG=trace
Error log:错误日志:
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`.
Note:笔记:
twitter
.存在一个名为twitter
的数据库。macros
for sqlx's dependency我已经包含了 sqlx 依赖项的macros
sqlx = {version="0.3.5", features = ["runtime-async-std", "macros", "chrono", "json", "postgres", "uuid"]}
Am I missing some level of authentication for connecting to database?我是否缺少用于连接数据库的某种级别的身份验证? I could not find it in docs for sqlx::Query
macro我在sqlx::Query
宏的文档中找不到它
The reason why it is unable to authenticate is that you must provide credentials before accessing the database无法进行身份验证的原因是您必须在访问数据库之前提供凭据
There are two ways to do it有两种方法可以做到
Option 1: Change your URL to contain the credentials - For instance -选项 1:更改您的 URL 以包含凭据 - 例如 -
DATABASE_URL=postgres://localhost?dbname=mydb&user=postgres&password=postgres
Option 2 Use PgConnectionOptions - For instance选项 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?;
Note: The sqlx version that I am using is sqlx = {version="0.5.1"}注意:我使用的 sqlx 版本是sqlx = {version="0.5.1"}
For more information refer the docs - https://docs.rs/sqlx/0.5.1/sqlx/postgres/struct.PgConnectOptions.html#method.password有关更多信息,请参阅文档 - https://docs.rs/sqlx/0.5.1/sqlx/postgres/struct.PgConnectOptions.html#method.password
Hope this helps you.希望这对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.