如何删除 linux 上的 postgresql 数据库

How to delete postgresql database on linux

我正在尝试使用命令行界面在 linux 上学习 postgresql。

不久前,我按照一些教程添加了一些数据库(我已经忘记了我学到的一切)。

现在我想删除这些数据库。

我假设我应该使用 psql(postgresql 的命令行界面)来执行此操作。

你可以在下面的命令行输出中看到我尝试了什么,其中 none 成功了。

psql (9.5.6)
Type "help" for help.

postgres=# \list
                                  List of databases
   Name    |  Owner   | Encoding |   Collate   |    Ctype    |   Access privileges   
-----------+----------+----------+-------------+-------------+-----------------------
 postgres  | postgres | UTF8     | en_CA.UTF-8 | en_CA.UTF-8 | 
 template0 | postgres | UTF8     | en_CA.UTF-8 | en_CA.UTF-8 | =c/postgres          +
           |          |          |             |             | postgres=CTc/postgres
 template1 | postgres | UTF8     | en_CA.UTF-8 | en_CA.UTF-8 | =c/postgres          +
           |          |          |             |             | postgres=CTc/postgres
 testdb    | postgres | UTF8     | en_CA.UTF-8 | en_CA.UTF-8 | 
(4 rows)

postgres=# dropdb template1
postgres-# \list
                                  List of databases
   Name    |  Owner   | Encoding |   Collate   |    Ctype    |   Access privileges   
-----------+----------+----------+-------------+-------------+-----------------------
 postgres  | postgres | UTF8     | en_CA.UTF-8 | en_CA.UTF-8 | 
 template0 | postgres | UTF8     | en_CA.UTF-8 | en_CA.UTF-8 | =c/postgres          +
           |          |          |             |             | postgres=CTc/postgres
 template1 | postgres | UTF8     | en_CA.UTF-8 | en_CA.UTF-8 | =c/postgres          +
           |          |          |             |             | postgres=CTc/postgres
 testdb    | postgres | UTF8     | en_CA.UTF-8 | en_CA.UTF-8 | 
(4 rows)

postgres-# DROP DATABASE template1
postgres-# \list
                                  List of databases
   Name    |  Owner   | Encoding |   Collate   |    Ctype    |   Access privileges   
-----------+----------+----------+-------------+-------------+-----------------------
 postgres  | postgres | UTF8     | en_CA.UTF-8 | en_CA.UTF-8 | 
 template0 | postgres | UTF8     | en_CA.UTF-8 | en_CA.UTF-8 | =c/postgres          +
           |          |          |             |             | postgres=CTc/postgres
 template1 | postgres | UTF8     | en_CA.UTF-8 | en_CA.UTF-8 | =c/postgres          +
           |          |          |             |             | postgres=CTc/postgres
 testdb    | postgres | UTF8     | en_CA.UTF-8 | en_CA.UTF-8 | 
(4 rows)

确保并以分号 (;) 结束您的 SQL 命令 尝试发出命令

DROP DATABASE template1;

分号在末尾。

是的,

DROP DATABASE template1;

并且不要忘记备份您的数据库:

要备份:pg_dump name_of_database > name_of_backup_file.bak

恢复:psql empty_database < backup_file.bak

如果您的数据库包含 'template1' 和 'template0' 数据库名称。您可以在下面使用我的脚本:

  1. 更新pg_database SET datistemplate='false' WHERE datname='template1';
  2. 删除数据库模板 1;