使用密码连接到 postgresql
本文展示了使用密码连接 postgresql 的各种方法。它可以通过命令行、pgpass
文件、pgpassword
环境变量或连接字符串。
使用命令行界面 (cli) 通过密码连接到 postgresql
如果你的机器上安装了 postgresql,你可以尝试不同的方法来连接数据库。一种简单的方法是在命令行中输入 psql
,它会询问你 admin
用户的密码。
如果你在命令中只输入 psql
而没有提及用户名,系统将询问你 postgresql 的管理员用户密码,如下所示。
c:\users\admin>psql
password for user admin:
如果你想使用其他帐户登录,则需要使用标志 -u
,然后提供用户名,如下所示。
c:\users\admin>psql -u postgres
password for user postgres:
psql (14.2)
warning: console code page (437) differs from windows code page (1252)
8-bit characters might not work correctly. see psql reference
page "notes for windows users" for details.
type "help" for help.
postgres=#
在这里,cli 要求输入用户 postgres
的密码。登录需要两个步骤。
首先,在 psql
命令中定义用户名,然后当 cli 询问时,你输入密码。但是我们可以使用一行命令直接连接到 postgresql。
为此,我们需要设置环境变量 pgpassword
。
在 windows 中:
c:\users\admin>set pgpassword=root
在 linux 中:
export pgpassword=root
如果我们想连接到 psql
,它将从 pgpassword
获取密码,该密码现在在环境中可用。
c:\users\admin>psql -u postgres
psql (14.2)
warning: console code page (437) differs from windows code page (1252)
8-bit characters might not work correctly. see psql reference
page "notes for windows users" for details.
type "help" for help.
你看,现在它不需要输入密码来连接 psql
。从了解有关 postgresql 环境变量的更多信息。
在 pgpass.conf
文件中定义密码以登录 postgresql
在 postgresql 的 appdata
文件夹中,有一个名为 pgpass.conf
的文件。你可以在那里定义你的密码。
此外,你可以使用连接参数 passfile
定义你的密码文件。文件格式如下。
hostname:port:database:username:password
这个结构在 postgresql 官方页面上提到过。
它知道用户有效的数据库以及该特定用户的密码。
使用带密码的连接字符串连接到 postgresql
当你获得不在 localhost
中的在线数据库或远程数据库时,你需要通过连接字符串进行连接。连接字符串包含一段用户名、密码、数据库名称、端口和主机地址。
连接字符串的格式如下。
postgresql://:@/?sslmode=require
如果你使用 localhost
,你不需要对远程数据库使用 sslmode
。在 python、c 或 java 项目中使用 postgresql 数据库时,此方法最有用。
因此,使用连接字符串连接数据库(本地)的命令如下。
c:\users\admin>psql postgresql://postgres:root@localhost:5432/postgres
psql (14.2)
warning: console code page (437) differs from windows code page (1252)
8-bit characters might not work correctly. see psql reference
page "notes for windows users" for details.
type "help" for help.
postgres=#
可用于客户端身份验证的方法列表。它来自 postgresql 官方文档。
转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处
本文地址:
相关文章
在一个 postgresql 查询中使用多个 with 语句
发布时间:2023/03/20 浏览次数:337 分类:postgresql
-
在本教程中,我们将学习如何使用多个 with 语句在 postgresql 中使用两个临时表执行查询。
发布时间:2023/03/20 浏览次数:185 分类:postgresql
-
本文介绍如何在 ubuntu 上找到 postgresql 数据库的配置文件。
发布时间:2023/03/20 浏览次数:409 分类:数据库
-
本文解释了如何直接从终端/命令行或 psql shell 运行 sql 文件。为此,你需要指定主机名、端口、用户名和数据库名称。
发布时间:2023/03/20 浏览次数:89 分类:postgresql
-
本文展示了如何列出 postgresql 上的活动连接。
发布时间:2023/03/20 浏览次数:966 分类:postgresql
-
在 pl/sql 中,你可能需要在 postgres 中使用循环。我们可以使用 for 和 while 语句来创建循环。
发布时间:2023/03/20 浏览次数:141 分类:postgresql
-
本文介绍如何在 postgresql 中仅使用单个查询来重命名列以及更改其类型。
发布时间:2023/03/20 浏览次数:233 分类:postgresql
-
本文介绍如何在 postgresql 中使用 select 方法连接列。
发布时间:2023/03/20 浏览次数:281 分类:postgresql
-
本文展示了如何使用 case 语句并给出了 postgresql 中的示例。