1 基本操作
psql -d db_name -U user_name -- 数据库连接
\l --列出数据库
\l t* --通配符,列出t打头的数据库,\dt等命令也可以
\c db_name --切换数据库
\dt -- 列出当前数据库中的表
select tablename from pg_tables; -- 查看所有表
\dt pg_tables -- 视图
\d table_name -- 查看表结构
\du -- 当前角色
2 系统信息函数(System Infomation Functions)
-- 当前数据库
select current_catalog;
select current_database();
-- 当前用户
select current_role;
select current_user;
select user;
-- 当前schema
select current_schema();
select current_schema;
-- pg版本
select version();
3 备份与恢复(pg_dump)
- 备份
-- 一般选项,输出的其实就是sql语句
pg_dump -h host -p port -U user -d database -f file
pg_dump -h 192.168.100.60 -p 5432 -U postgres -d test -f g:\test.sql
-- 输出文件可以使用 '-f' 或 '>'
pg_dump -U postgres -d test > g:\test.sql
-- 指定表
pg_dump -U postgres -d test -t tb1 -t tb2 > g:\test.sql -- 输出t1和t2
pg_dump ... -T tb1 -T tb2 ... -- 不输出t1和t2
-- 复杂的
pg_dump ... -t t1 -a --inserts ... -- 以insert语句导出t1的数据,默认使用copy
pg_dump ... -n public -s ... -- 导出public schema的所有表的结构
- 恢复(psql)
-- 需要先创建数据库
psql -h host -p post -U user -d database -f file
-- -f参数表示从文件执行
psql -U postgres -d test -f g:\test.sql
psql -U postgres -d test < g:\test.sql -- 也可以使用'<'
参考
https://www.postgresql.org/docs/10/static/functions-info.html