查看数据库版本
1
2psql -V
psql --version1
dbname=# select version();
命令行查询结果输出到文件
1
2dbname=# \o filename
dbname=# \o select * from table;导出tabname表数据的insert语句sql
1
pg_dump -h localhost -U username -d dbname --table tabname --data-only --column-inserts > tabname_insert.sql
命令行常用命令
\l show database
\dt show tables
\di show index
\du show users
\df show functions
\c db_name use database
\c db_name username serverIP port
\d tablename show table info
select pg_database_size(‘db_name’); 查看数据库大小
select pg_relation_size(‘table_name’); 查看表大小
select pg_size_pretty(pg_relation_size(‘table_name’)); 以KB,MB,GB的方式来查看表大小
select pg_size_pretty(pg_total_relation_size(‘table_name’)); 查看表的总大小,包括索引大小
select spcname from pg_tablespace; 查看所有表空间
select pg_size_pretty(pg_tablespace_size(‘pg_default’)); 查看表空间大小
\q quit
备份数据库
$ pg_dump -h host -U username -f ./backup.sql dbname
仅备份结构
$ pg_dump -h host -U username -f ./backup.sql -s dbname
删除数据库
$ dropdb -h localhost -p 5432 -U postgres dbname
dbname=# drop database dbname;
删除活动连接
dbname=# select pg_terminate_backend(pid) from pg_stat_activity where datname = 'dbname' and pid <>pg_backend_pid()
创建数据库
dbname=# create database dbname owner username;
修改数据库
dbname=# alter database dbname owner to new_user;
分配权限
dbname=# grant all privileges on database dbname to user;
恢复数据库
$ psql -h localhost -U postgres -d dbname < backup.sql