Postgresql数据库提供一种在shell下创建数据库的工具:createdb
createdb不是特殊的工具,可以说它是数据库创建命令的整合工具。它连接到postgres数据库并发出CREATE database命令,与在进入Postgresql数据库中执行 CREATE DATABASE 是一样的。可以看作是脚本命令。
createdb [connection-option…] [option…] [dbname [description]]
语法解析(createdb命令接受一下参数来执行创建数据库时指定的各个参数):
1.dbname:执行新数据库的名称,不与现有数据库名称冲突,默认设置是创建与当前系统用户同名的数据库。
2.description:指定要与新创建的数据库关联的注释。
3.-D tablespace 或 --tablespace=tablespace:指定新数据库的默认表空间(注意表空间名称要加上双引号)
4.-e 或 --echo:显示 createdb 生成的并发送给数据库服务的相关命令详情。
5.-E encoding 或 --encoding=encoding:执行新数据库的字符集编码(字符集名称加双引号)。
6.-l locale 或 --locale=locale:指定此数据库中使用的语言环境。这相当于同时指定——lc-collate和——lc-ctype。
7.–lc-collate=locale:指定要在此数据库中使用的LC_COLLATE设置。
8.–lc-ctype=locale:指定要在此数据库中使用的LC_CTYPE设置。
9.-O owner 或 --owner=owner:指定将拥有新数据库的数据库用户。(此名称作为双引号标识符处理。)
10.-T template 或 --template=template:指定要从中构建此数据库的模板数据库。(此名称作为双引号标识符处理。)
11.-V 或 --version:打印 createdb 工具的版本。
12.-? 或 --help:帮助命令。
以上时createdb 工具创建数据库时所支持的参数指定,另外它还支持链接参数:
-h host
–host=host
Specifies the host name of the machine on which the server is running. If the value begins with a slash, it is used as the directory for the Unix domain socket.
-p port
–port=port
Specifies the TCP port or the local Unix domain socket file extension on which the server is listening for connections.
-U username
–username=username
User name to connect as.
-w
–no-password
Never issue a password prompt. If the server requires password authentication and a password is not available by other means such as a .pgpass file, the connection attempt will fail. This option can be useful in batch jobs and scripts where no user is present to enter a password.
-W
–password
Force createdb to prompt for a password before connecting to a database.
This option is never essential, since createdb will automatically prompt for a password if the server demands password authentication. However, createdb will waste a connection attempt finding out that the server wants a password. In some cases it is worth typing -W to avoid the extra connection attempt.
–maintenance-db=dbname
Specifies the name of the database to connect to when creating the new database. If not specified, the postgres database will be used; if that does not exist (or if it is the name of the new database being created), template1 will be used.
1.PGDATABASE:If set, the name of the database to create, unless overridden on the command line.
2.PGHOST
3.PGPORT
4.PGUSER:Default connection parameters. PGUSER also determines the name of the database to create, if it is not specified on the command line or by PGDATABASE.
5.PG_COLOR:Specifies whether to use color in diagnostics messages. Possible values are always, auto, never.
To create the database demo using the default database server:
$ createdb demo
To create the database demo using the server on host eden, port 5000, using the template0 template database, here is the command-line command and the underlying SQL command:
$ createdb -p 5000 -h eden -T template0 -e demo
CREATE DATABASE demo TEMPLATE template0;