postgresql Postgres 在特定数据库中创建架构
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11949401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Postgres Creating Schema in a specific database
提问by AVA
I got one suggestion form stackoverflow.com to create schema in a specific database as follows:
我从 stackoverflow.com 收到了一份建议,用于在特定数据库中创建架构,如下所示:
CREATE DATABASE foo;
\connect foo;
CREATE SCHEMA yourschema;
But I am getting error as follows:
但我收到如下错误:
ERROR: syntax error at or near "\" LINE 2: \connect foo; ^
***Error ***
ERROR: syntax error at or near "\"
错误:“\”处或附近的语法错误第 2 行:\connect foo; ^
***错误 ** *
错误:“\”处或附近的语法错误
Situation :
情况 :
Login as postgress
create user u1
create database db1 with owner u1
\connect u1
create schema s1
以 postgress 身份登录
create user u1
create database db1 with owner u1
\connect u1
create schema s1
Please help me in creating schema in a specific db.
请帮助我在特定数据库中创建架构。
回答by Berry Langerak
This works, if - and only if- you're using psql:
这有效,如果 -并且仅当- 您正在使用 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
is a psql command. It's not normal SQL, so you can't use that in a .sql file. There is no way to do it from within a sql file, as far as I know. The rationale behind this, is that you should reconnect to a different database once you want to use that different database. This is for database separation. The reason MySQL has implemented the use $database
syntax is because of it's lack of schema's, but PostgreSQL doesn't have a command like that, as a database should be separated in schema's, rather than databases.
\connect
是一个 psql 命令。它不是普通的 SQL,因此您不能在 .sql 文件中使用它。据我所知,无法从 sql 文件中执行此操作。这背后的基本原理是,一旦您想使用不同的数据库,就应该重新连接到不同的数据库。这是为了数据库分离。MySQL 实现use $database
语法的原因是因为它缺少模式,但 PostgreSQL 没有这样的命令,因为数据库应该在模式中分开,而不是在数据库中。