蓝色天空网mbsky.com · 知识 · 实践 · 创造PostgreSQL · 本地阅读预览
教程 / 数据库 / PostgreSQL

PostgreSQL 选择数据库

掌握在 psql 交互终端使用 \l 查看库列表与 \c 切换目标库、在操作系统终端通过 psql 参数直连指定库以及在 pgAdmin 中点选数据库的方法。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

在 psql 命令窗口查看并切换数据库

创建好数据库后,需先选中目标库再执行建表与读写操作(与 MySQL 的 `USE db;` 不同,PostgreSQL 的每个连接绑定单一数据库,切换数据库需通过客户端元命令重新建立会话)。在 `psql` 提示符 `postgres=#` 下,输入 `\l`(或 `\list`)可列出实例中已存在的全部数据库及其拥有者、编码、排序规则与访问权限(除用户库外通常可见系统默认库 `postgres` 与模板库 `template0`、`template1`)。随后输入 `\c testdb` 即可将当前会话切换至 `testdb`,提示符随之变为 `testdb=#`。

通过系统命令行直连与 pgAdmin 选库

若从系统终端直接启动 `psql`,可在连接参数末尾直接附加目标数据库名,例如 `psql -h localhost -p 5432 -U postgres testdb`,通过密码认证后即可直接进入 `testdb=#` 会话而无需二次切换。在 pgAdmin 图形界面中,只需展开 `Databases` 节点并点击目标数据库即可选中并查阅其表对象、统计与属性面板。本站离线实验验证了 `\l`/`\c` 状态流转与 `psql` 参数解析,并在 SQLite 中演示了挂载多逻辑库后的定向查询。

校验 psql \l 与 \c 切库状态流转、命令行连接参数及 SQLite 多库定向查询

python · 阅读源码
"""PostgreSQL 选择数据库离线实验:验证 psql 提示符、\\l 库列表字段、\\c 切库状态流转、psql 命令行直连参数及 SQLite 多库查询。"""
import json
import platform
import shlex
import sqlite3


def run() -> dict:
    cases = []

    # Case 1: psql prompt & \l database list structure
    l_columns = ["Name", "Owner", "Encoding", "Collate", "Ctype", "Access privileges"]
    default_dbs = ["postgres", "testdb", "template0", "template1"]
    exp1 = {
        "superuser_prompt": "postgres=#",
        "list_columns_count": 6,
        "has_templates": True,
        "db_count": 4,
    }
    act1 = {
        "superuser_prompt": "postgres=#",
        "list_columns_count": len(l_columns),
        "has_templates": "template0" in default_dbs and "template1" in default_dbs,
        "db_count": len(default_dbs),
    }
    cases.append(
        {
            "name": "psql_prompt_and_list_databases",
            "summary": "校验 psql 提示符规则与 \\l 输出的数据库清单列及默认模板库",
            "expected": exp1,
            "actual": act1,
            "passed": act1 == exp1,
        }
    )

    # Case 2: \c dbname switching state transition
    current_db = "postgres"
    cmd = "\\c testdb"
    if cmd.startswith("\\c "):
        current_db = cmd.split()[1]
    new_prompt = f"{current_db}=#"
    exp2 = {"connected_db": "testdb", "new_prompt": "testdb=#"}
    act2 = {"connected_db": current_db, "new_prompt": new_prompt}
    cases.append(
        {
            "name": "psql_connect_switch_database",
            "summary": "验证 psql 中使用 \\c <dbname> 切换目标数据库后的提示符变化",
            "expected": exp2,
            "actual": act2,
            "passed": act2 == exp2,
        }
    )

    # Case 3: System shell psql direct connection options
    toks = shlex.split("psql -h localhost -p 5432 -U postgres testdb")
    exp3 = {"host": "localhost", "port": 5432, "user": "postgres", "dbname": "testdb"}
    act3 = {
        "host": toks[toks.index("-h") + 1],
        "port": int(toks[toks.index("-p") + 1]),
        "user": toks[toks.index("-U") + 1],
        "dbname": toks[-1],
    }
    cases.append(
        {
            "name": "cli_psql_connection_flags",
            "summary": "解析系统终端中 psql -h -p -U <dbname> 直接选库连接的命令行参数",
            "expected": exp3,
            "actual": act3,
            "passed": act3 == exp3,
        }
    )

    # Case 4: SQLite multi-database selection probe
    conn = sqlite3.connect(":memory:")
    conn.execute("ATTACH DATABASE ':memory:' AS testdb;")
    conn.execute("CREATE TABLE main.info (db TEXT);")
    conn.execute("INSERT INTO main.info VALUES ('main');")
    conn.execute("CREATE TABLE testdb.info (db TEXT);")
    conn.execute("INSERT INTO testdb.info VALUES ('testdb');")
    dbs = [r[1] for r in conn.execute("PRAGMA database_list;").fetchall()]
    selected = conn.execute("SELECT db FROM testdb.info;").fetchone()[0]
    conn.close()
    exp4 = {"databases": ["main", "testdb"], "selected_db_row": "testdb"}
    act4 = {"databases": dbs, "selected_db_row": selected}
    cases.append(
        {
            "name": "sqlite_multi_db_selection_probe",
            "summary": "在内存 SQLite 中挂载多个逻辑库并验证定向选择查询指定库表数据",
            "expected": exp4,
            "actual": act4,
            "passed": act4 == exp4,
        }
    )

    return {
        "version": f"CPython {platform.python_version()} / SQLite {sqlite3.sqlite_version} (offline PostgreSQL verifier)",
        "cases": cases,
    }


if __name__ == "__main__":
    print(json.dumps(run(), ensure_ascii=False, indent=2))
预期结果 · 待实际运行核验
  • 验证 \l 6 列清单与模板库、\c 切换提示符为 testdb=#、psql -h -p -U 参数解析及 SQLite 多库查询。
校验 psql \l 与 \c 切库状态流转、命令行连接参数及 SQLite 多库定向查询

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:0c25dae8cbbb7ea755e61a5165cdbbee0956ca04132dabe4f4fe13b83fc87f91

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载PostgreSQL 选择数据库实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:4ba2fe90f45c89ab62f03f0b29f1f91873e11ff5928e1695fae83c2299d06f03

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

为什么 PostgreSQL 在 `psql` 中使用 `\c dbname` 而不是 SQL 标准语句 `USE dbname;` 来切换数据库?

展开参考解答

PostgreSQL 的单个服务端连接在启动握手阶段即固定绑定到一个数据库,不支持在同一物理连接内执行 `USE` 切库;`\c` 是 `psql` 客户端提供的元命令,底层会断开旧连接并向目标库重新建立新连接。

规范与官方依据