- 所有
\
开头的命令必须使用 postgresql 自带的可执行程序; - postgresql 提供的程序大小写敏感;
创建数据库
CREATE DATABASE dbname;
- PostgreSQL bin 目录下有几个可执行文件:可以没事儿到bin目录多看看
clusterdb.exe
createdb.exe
createuser.exe
dropdb.exe
dropuser.exe
ecpg.exe
...
psql.exe
- 其中 createdb.exe 可用用来创建数据库 :
createdb -h localhost -p 5432 -U postgres db_name
; - pgAdmin 也可以用来创建数据库;在DataBase 上右键按提示操作即可;
选择数据库
- 在命令行中:
- 查看已经存在的库:
\l
- 选择数据库进入:
\c db_name
- 进入命令行时直接选好数据库进入:
psql -h localhost -p 5432 -U postgres db_name
;psql -h 127.0.0.1 -p 5432 -U administrator postgres
删除数据库
- 在命令行中:
DROP DATABASE [ IF EXISTS ] db_name
, drop database if exists db_name
; - 使用bin 目录下的可执行文件:
dropdb -h localhost -p 5432 -U postgres db_name
;
建表
CREATE TABLE "public"."tb_name" (
"id" int4 NOT NULL,
"name" varchar(255) NOT NULL,
"age" int4,
"remark" varchar(255),
PRIMARY KEY ("id", "name")
)
;
- 查看表:
\d table_name
; \d
列出所有表;
删表
DROP TABLE table_name,table_name2;
关于模式
- 模式类似于操作系统层的目录,也类似于linux 命名空间;但是模式不能嵌套。
- PostgreSQL 模式(schema)可以看着是一个表的集合。
- 相同的对象名称可以被用于不同的模式中而不会出现冲突,例如 schema1 和 schema2 都可以包含名为 table_name 的表。
- 主要用于将数据库对象组织成逻辑组以便更容易管理。
模式的增删 和表一起操作
create schema schema_name;
select * from schema_name.table_name;
drop schema schema_name;
drop schema myschema cascade;
创建用户
create user Administrator with password 'root';
grant all privileges on database postgres to Administrator;
grant all privileges on all tables in schema public to Administrator;
示例
D:\devware\postgresql14\app_dir\bin> psql -h 127.0.0.1 -p 5432 -U administrator postgres
用户 administrator 的口令:
psql (14.1)
输入 "help" 来获取帮助信息.
postgres=> help
您正在使用psql, 这是一种用于访问PostgreSQL的命令行界面.
键入: \copyright 显示发行条款
\h 显示 SQL 命令的说明
\? 显示 pgsql 命令的说明
\g 或者以分号(;)结尾以执行查询
\q 退出
postgres=> \d
关联列表
架构模式 | 名称 | 类型 | 拥有者
----------+--------------+--------+----------
public | tb_test_name | 数据表 | postgres
(1 行记录)
postgres=> \l
数据库列表
名称 | 拥有者 | 字元编码 | 校对规则 | Ctype | 存取权限
-----------+----------+----------+----------+-------+----------------------------
postgres | postgres | UTF8 | C | C | =Tc/postgres +
| | | | | postgres=CTc/postgres +
| | | | | administrator=CTc/postgres
template0 | postgres | UTF8 | C | C | =c/postgres +
| | | | | postgres=CTc/postgres
template1 | postgres | UTF8 | C | C | =c/postgres +
| | | | | postgres=CTc/postgres
(3 行记录)
postgres=> \q
D:\devware\postgresql14\app_dir\bin> psql -h 127.0.0.1 -p 5432 -U postgres postgres
用户 postgres 的口令:
psql (14.1)
输入 "help" 来获取帮助信息.
postgres=