这有效,当且仅当您使用 psql 时:
postgres@berry-pc:~$ psql template1
psql (8.4.10)
Type "help" for help.
template1=# CREATE DATABASE foo;
CREATE DATABASE
template1=# \connect foo;
psql (8.4.10)
You are now connected to database "foo".
foo=# \connect template1
psql (8.4.10)
You are now connected to database "template1".
template1=# DROP DATABASE foo;
DROP DATABASE
template1=# \q
\connect是一个 psql 命令。这不是普通的 SQL,因此您不能在 .sql 文件中使用它。据我所知,无法从 sql 文件中执行此操作。这背后的基本原理是,一旦您想使用不同的数据库,就应该重新连接到不同的数据库。这是为了数据库分离。MySQL 实现use $database语法的原因是因为它缺少模式,但 PostgreSQL 没有这样的命令,因为数据库应该在模式而不是数据库中分开。