PostgreSQL - 选择数据库
PostgreSQL - 连接到数据库
Section titled “PostgreSQL - 连接到数据库”要在 PostgreSQL 中使用数据,您首先需要建立与特定数据库的连接。您可以使用命令行界面 (psql)、现代 GUI 工具,或者直接从您的应用程序代码中使用连接字符串来完成此操作。
方法 1:使用 psql 命令行界面
Section titled “方法 1:使用 psql 命令行界面”psql 是 PostgreSQL 强大且交互式的终端工具。它是任何开发人员或管理员的必备工具。
直接从您的 Shell 连接
Section titled “直接从您的 Shell 连接”您可以在启动 psql 时,通过将数据库名称作为最后一个参数提供,直接连接到特定数据库。其他常用参数包括 -U(用户)、-h(主机)和 -p(端口)。
# Connect to the 'testdb' database as user 'postgres' on the local machine# 以用户 'postgres' 身份连接到本地机器上的 'testdb' 数据库psql -U postgres -d testdb
# You will be prompted for a password# 系统将提示您输入密码Password for user postgres:
# Successful connection prompt (version may vary)# 成功连接提示(版本可能有所不同)psql (16.0)Type "help" for help.
testdb=>提示符 testdb=> 表示您已连接到 testdb 数据库。
在 psql 内部切换数据库
Section titled “在 psql 内部切换数据库”如果您已经身处 psql 内部,可以使用 \l 命令列出所有可用数据库,并使用 \c [database_name] 命令切换到不同的数据库。
postgres=> \l List of databases Name | Owner | Encoding | Collate | Ctype | Access privileges-----------+----------+---------+---------+---------+----------------------- postgres | postgres | UTF8 | C.UTF-8 | C.UTF-8 | template0 | postgres | UTF8 | C.UTF-8 | C.UTF-8 | =c/postgres ... template1 | postgres | UTF8 | C.UTF-8 | C.UTF-8 | =c/postgres ... testdb | postgres | UTF8 | C.UTF-8 | C.UTF-8 |(4 rows)
postgres=> \c testdbYou are now connected to database "testdb" as user "postgres".-- 您现在已连接到数据库 "testdb",用户为 "postgres"。testdb=>要随时退出 psql,请使用 \q 命令。
方法 2:现代连接方法
Section titled “方法 2:现代连接方法”连接 URI
Section titled “连接 URI”连接 URI(统一资源标识符)是一种标准化的字符串格式,用于指定连接详细信息。它被编程语言、库(如 Node.js 的 pg 或 Python 的 psycopg2)和 GUI 工具广泛使用,因为它将所有必要信息封装在一个字符串中。
格式如下:
postgresql://[user[:password]@]host[:port]/dbname[?options]示例:
postgresql://postgres:mysecretpassword@localhost:5432/testdbGUI 数据库工具
Section titled “GUI 数据库工具”为了获得更直观、用户友好的体验,许多开发人员使用图形用户界面(GUI)工具来连接和管理他们的数据库。这些工具提供了诸如模式浏览、带语法高亮的查询编辑器和数据可视化等功能。
流行的 PostgreSQL GUI 工具包括:
- pgAdmin: PostgreSQL 的官方开源管理工具。
- DBeaver: 一个免费的通用数据库工具,支持包括 PostgreSQL 在内的多种数据库系统。
- DataGrip: JetBrains 出品的一款功能强大的商业数据库 IDE。
- Postico (macOS): macOS 上一款简洁现代的 PostgreSQL 原生客户端。
所有这些工具都将要求提供相同的基本连接参数:主机 (Host)、端口 (Port)、数据库名称 (Database Name)、用户 (User) 和密码 (Password)。