2012-08-14 84 views
6

我有一个建议的形式stackoverflow.com在特定的数据库中创建架构如下:的Postgres在特定数据库创建模式

CREATE DATABASE foo; 
\connect foo; 
CREATE SCHEMA yourschema; 

但我得到的错误如下:

ERROR: syntax error at or near "\" LINE 2: \connect foo; ^

*** Error ***

ERROR: syntax error at or near "\"

现状:

登录为postgress
创建用户U1
创建数据库DB 1所有者U1
\连接U1
创建模式S1

请帮我在一个特定的数据库创建模式。

+0

你如何连接到数据库?你用'psql'命令行工具来做这件事吗? – 2012-08-14 09:37:13

回答

9

这工作,如果 - 且仅当 - 你正在使用的psql:

[email protected]:~$ 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没有这样的命令,因为数据库应该在模式中而不是数据库中分开。