postgresql |数据库 |postgresql数据库的短命令详细介绍

本文涉及的产品
云原生数据库 PolarDB MySQL 版,Serverless 5000PCU 100GB
简介: postgresql |数据库 |postgresql数据库的短命令详细介绍

前言:

postgresql数据库相比较MySQL或者oracle,一个是开源优势,另一个就是postgresql数据库的命令行更为丰富,因此,数据库的管理工作更为方便,快捷,尤其是postgresql的短命令就可以基本满足日常的数据库维护,管理工作了。

####注:短命令通常是用在pg的命令行客户端的,也就是psql -U用户  -p 端口 -h 数据库IP 登陆数据库后 \c 这样的命令,我们称之为短命令,无需通过客户端登陆数据库服务端的,例如pg_controldata ,pg_dump 这些命令我们称之为长命令。

下面就postgresql的短命令做一个详细的介绍

一,

查询短命令有哪些?

\?是帮助查询命令

test=# \?
General
  \copyright             show PostgreSQL usage and distribution terms
  \crosstabview [COLUMNS] execute query and display results in crosstab
  \errverbose            show most recent error message at maximum verbosity
  \g [FILE] or ;         execute query (and send results to file or |pipe)
  \gdesc                 describe result of query, without executing it
  \gexec                 execute query, then execute each value in its result
  \gset [PREFIX]         execute query and store results in psql variables
  \gx [FILE]             as \g, but forces expanded output mode
  \q                     quit psql
  \watch [SEC]           execute query every SEC seconds
Help
  \? [commands]          show help on backslash commands
  \? options             show help on psql command-line options
  \? variables           show help on special variables
  \h [NAME]              help on syntax of SQL commands, * for all commands
Query Buffer
  \e [FILE] [LINE]       edit the query buffer (or file) with external editor
  \ef [FUNCNAME [LINE]]  edit function definition with external editor
  \ev [VIEWNAME [LINE]]  edit view definition with external editor
  \p                     show the contents of the query buffer
  \r                     reset (clear) the query buffer
  \s [FILE]              display history or save it to file
  \w FILE                write query buffer to file
Input/Output
  \copy ...              perform SQL COPY with data stream to the client host
  \echo [STRING]         write string to standard output
  \i FILE                execute commands from file
  \ir FILE               as \i, but relative to location of current script
  \o [FILE]              send all query results to file or |pipe
  \qecho [STRING]        write string to query output stream (see \o)
Conditional
  \if EXPR               begin conditional block
  \elif EXPR             alternative within current conditional block
  \else                  final alternative within current conditional block
  \endif                 end conditional block
Informational
  (options: S = show system objects, + = additional detail)
  \d[S+]                 list tables, views, and sequences
  \d[S+]  NAME           describe table, view, sequence, or index
  \da[S]  [PATTERN]      list aggregates
  \dA[+]  [PATTERN]      list access methods
  \db[+]  [PATTERN]      list tablespaces
  \dc[S+] [PATTERN]      list conversions
  \dC[+]  [PATTERN]      list casts
  \dd[S]  [PATTERN]      show object descriptions not displayed elsewhere
  \dD[S+] [PATTERN]      list domains
  \ddp    [PATTERN]      list default privileges
  \dE[S+] [PATTERN]      list foreign tables
  \det[+] [PATTERN]      list foreign tables
  \des[+] [PATTERN]      list foreign servers
  \deu[+] [PATTERN]      list user mappings
  \dew[+] [PATTERN]      list foreign-data wrappers
  \df[anptw][S+] [PATRN] list [only agg/normal/procedures/trigger/window] functions
  \dF[+]  [PATTERN]      list text search configurations
  \dFd[+] [PATTERN]      list text search dictionaries
  \dFp[+] [PATTERN]      list text search parsers
  \dFt[+] [PATTERN]      list text search templates
  \dg[S+] [PATTERN]      list roles
  \di[S+] [PATTERN]      list indexes
  \dl                    list large objects, same as \lo_list
  \dL[S+] [PATTERN]      list procedural languages
  \dm[S+] [PATTERN]      list materialized views
  \dn[S+] [PATTERN]      list schemas
  \do[S]  [PATTERN]      list operators
  \dO[S+] [PATTERN]      list collations
  \dp     [PATTERN]      list table, view, and sequence access privileges
  \dP[itn+] [PATTERN]    list [only index/table] partitioned relations [n=nested]
  \drds [PATRN1 [PATRN2]] list per-database role settings
  \dRp[+] [PATTERN]      list replication publications
  \dRs[+] [PATTERN]      list replication subscriptions
  \ds[S+] [PATTERN]      list sequences
  \dt[S+] [PATTERN]      list tables
  \dT[S+] [PATTERN]      list data types
  \du[S+] [PATTERN]      list roles
  \dv[S+] [PATTERN]      list views
  \dx[+]  [PATTERN]      list extensions
  \dy     [PATTERN]      list event triggers
  \l[+]   [PATTERN]      list databases
  \sf[+]  FUNCNAME       show a function's definition
  \sv[+]  VIEWNAME       show a view's definition
  \z      [PATTERN]      same as \dp
Formatting
  \a                     toggle between unaligned and aligned output mode
  \C [STRING]            set table title, or unset if none
  \f [STRING]            show or set field separator for unaligned query output
  \H                     toggle HTML output mode (currently off)
  \pset [NAME [VALUE]]   set table output option
                         (border|columns|csv_fieldsep|expanded|fieldsep|
                         fieldsep_zero|footer|format|linestyle|null|
                         numericlocale|pager|pager_min_lines|recordsep|
                         recordsep_zero|tableattr|title|tuples_only|
                         unicode_border_linestyle|unicode_column_linestyle|
                         unicode_header_linestyle)
  \t [on|off]            show only rows (currently off)
  \T [STRING]            set HTML <table> tag attributes, or unset if none
  \x [on|off|auto]       toggle expanded output (currently off)
Connection
  \c[onnect] {[DBNAME|- USER|- HOST|- PORT|-] | conninfo}
                         connect to new database (currently "test")
  \conninfo              display information about current connection
  \encoding [ENCODING]   show or set client encoding
  \password [USERNAME]   securely change the password for a user
Operating System
  \cd [DIR]              change the current working directory
  \setenv NAME [VALUE]   set or unset environment variable
  \timing [on|off]       toggle timing of commands (currently off)
  \! [COMMAND]           execute command in shell or start interactive shell
Variables
  \prompt [TEXT] NAME    prompt user to set internal variable
  \set [NAME [VALUE]]    set internal variable, or list all if no parameters
  \unset NAME            unset (delete) internal variable
Large Objects
  \lo_export LOBOID FILE
  \lo_import FILE [COMMENT]
  \lo_list
  \lo_unlink LOBOID      large object operations

可以看到,短命令按类别分了很多种,但,其中有一些命令是非常常用的,可以有效提高数据库运维,管理工作的,

因此,一些不太常用的或者使用率比较低的短命令,本文将会略过或者只是简单的介绍。

二,

连接方面的查询的短命令(非常常用的)

test=# \c 
You are now connected to database "test" as user "postgres".
test=# \conninfo
You are connected to database "test" as user "postgres" via socket in "/tmp" at port "5432".
test=# \password postgres
Enter new password: 
Enter it again:

以上命令 \c 是显示简略连接信息,本例是使用超级用户postgres连接到了 名为test的数据库

\conninfo 是连接详细信息,本例是使用超级用户postgres连接到了 名为test的数据库,socket文件是/tmp目录下,连接端口是5432

\password postgres是快速d修改的,安全的修改用户密码,不过通常是postgres这个超级用户才可以修改其它用户密码,本例是修改本用户postgres的密码

三,

各类信息查询,主要是数据库,表,索引,外键,主键

查询当前连接的数据库或者schema内的表名称 \d+ 多显示表的大小以及所属这些信息。

test=# \d
        List of relations
 Schema | Name | Type  |  Owner   
--------+------+-------+----------
 mytest | emp  | table | postgres
(1 row)
test=# \d+
                   List of relations
 Schema | Name | Type  |  Owner   | Size  | Description 
--------+------+-------+----------+-------+-------------
 mytest | emp  | table | postgres | 16 kB | 
(1 row)

仅查询表和视图:

test-# \dp
                                      Access privileges
 Schema |         Name         |   Type   | Access privileges | Column privileges | Policies 
--------+----------------------+----------+-------------------+-------------------+----------
 public | audit                | table    |                   |                   | 
 public | bonus                | table    |                   |                   | 
 public | company              | table    |                   |                   | 
 public | dept                 | table    |                   |                   | 
 public | emp                  | table    |                   |                   | 
 public | history_table        | table    |                   |                   | 
 public | history_table_id_seq | sequence |                   |                   | 
 public | salgrade             | table    |                   |                   | 
 public | tmp                  | table    |                   |                   | 
 public | 計算機用語           | table    |                   |                   | 
(10 rows)

查询有哪些数据库,以及数据库的大小:

test-# \l
                                List of databases
   Name    |  Owner   | Encoding |   Collate   |    Ctype    | Access privileges 
-----------+----------+----------+-------------+-------------+-------------------
 pg1       | pg1      | UTF8     | en_US.UTF-8 | en_US.UTF-8 | 
 postgres  | pg1      | UTF8     | en_US.UTF-8 | en_US.UTF-8 | 
 template0 | pg1      | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/pg1           +
           |          |          |             |             | pg1=CTc/pg1
 template1 | pg1      | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/pg1           +
           |          |          |             |             | pg1=CTc/pg1
 test      | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | 
(5 rows)
test-# \l+
                                                                  List of databases
   Name    |  Owner   | Encoding |   Collate   |    Ctype    | Access privileges |  Size   | Tablespace |                Description 
-----------+----------+----------+-------------+-------------+-------------------+---------+------------+----------------------------
----------------
 pg1       | pg1      | UTF8     | en_US.UTF-8 | en_US.UTF-8 |                   | 7953 kB | pg_default | 
 postgres  | pg1      | UTF8     | en_US.UTF-8 | en_US.UTF-8 |                   | 7993 kB | pg_default | default administrative conn
ection database
 template0 | pg1      | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/pg1           +| 7809 kB | pg_default | unmodifiable empty database
           |          |          |             |             | pg1=CTc/pg1       |         |            | 
 template1 | pg1      | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/pg1           +| 7809 kB | pg_default | default template for new da
tabases
           |          |          |             |             | pg1=CTc/pg1       |         |            | 
 test      | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 |                   | 8849 kB | pg_default | 
(5 rows)

 

 

查询具体表结构,索引,或者视图,根据以上命令,在继续详细查询emp表和它的主键详细信息:

test=# \d emp
                        Table "mytest.emp"
  Column  |         Type          | Collation | Nullable | Default 
----------+-----------------------+-----------+----------+---------
 empno    | numeric               |           | not null | 
 ename    | character varying(10) |           |          | 
 job      | character varying(9)  |           |          | 
 mgr      | numeric               |           |          | 
 hiredate | date                  |           |          | 
 sal      | numeric(7,2)          |           |          | 
 comm     | numeric(7,2)          |           |          | 
 deptno   | numeric(2,0)          |           |          | 
Indexes:
    "pk_emp" PRIMARY KEY, btree (empno)
test=# \d pk_emp
        Index "mytest.pk_emp"
 Column |  Type   | Key? | Definition 
--------+---------+------+------------
 empno  | numeric | yes  | empno
primary key, btree, for table "mytest.emp"

查询该数据库支持的访问方法:

test=# \dA+
                             List of access methods
  Name  | Type  |       Handler        |              Description               
--------+-------+----------------------+----------------------------------------
 brin   | Index | brinhandler          | block range index (BRIN) access method
 btree  | Index | bthandler            | b-tree index access method
 gin    | Index | ginhandler           | GIN index access method
 gist   | Index | gisthandler          | GiST index access method
 hash   | Index | hashhandler          | hash index access method
 heap   | Table | heap_tableam_handler | heap table access method
 spgist | Index | spghandler           | SP-GiST index access method
(7 rows)

查询现有的表空间有哪些,+显示表空间的大小:

test=# \db
      List of tablespaces
    Name    | Owner | Location 
------------+-------+----------
 pg_default | pg1   | 
 pg_global  | pg1   | 
(2 rows)
test=# \db+
                                List of tablespaces
    Name    | Owner | Location | Access privileges | Options |  Size  | Description 
------------+-------+----------+-------------------+---------+--------+-------------
 pg_default | pg1   |          |                   |         | 40 MB  | 
 pg_global  | pg1   |          |                   |         | 623 kB | 
(2 rows)

查询函数,普通函数,以及和触发器相关的函数:

test=# \df
                                                                               List of functions
 Schema |        Name         | Result data type  |                                                 Argument data types              
                                    | Type 
--------+---------------------+-------------------+----------------------------------------------------------------------------------
------------------------------------+------
 public | __tmp_create_user   | void              |                                                                                  
                                    | func
 public | auditlogfunc        | trigger           |                                                                                  
                                    | func
 public | copytable           | integer           | new_table_name character varying, old_table_name character varying, times integer
                                    | func
 public | emp                 | void              | arr text[]                                                                       
                                    | func
 public | emp_history_trigger | trigger           |                                                                                  
                                    | func
后面的略略略
test=# \dfn
                                                                              List of functions
 Schema |       Name        | Result data type  |                                                 Argument data types                
                                  | Type 
--------+-------------------+-------------------+------------------------------------------------------------------------------------
----------------------------------+------
 public | __tmp_create_user | void              |                                                                                    
                                  | func
 public | copytable         | integer           | new_table_name character varying, old_table_name character varying, times integer  
                                  | func
 public | emp               | void              | arr text[]                                                                         
                                  | func
 public | f_inittables1     | void              | arr text[]                                                                         
                                  | func
 public | ftest             | character varying | fname character varying DEFAULT '水果'::character varying, cname character varying 
DEFAULT '西瓜'::character varying | func
 public | getsum            | integer           | talename character varying                                                         
                                  | func
 public | test              | void              | arr text[]                                                                         
                                  | func
 public | totalrecords      | integer           |                                                                                    
                                  | func
(8 rows)
test=# \dft
                              List of functions
 Schema |        Name         | Result data type | Argument data types | Type 
--------+---------------------+------------------+---------------------+------
 public | auditlogfunc        | trigger          |                     | func
 public | emp_history_trigger | trigger          |                     | func
 public | record_history      | trigger          |                     | func
(3 rows)

查询所有用户和用户的详细信息:

test-# \dg
                                        List of roles
     Role name      |                         Attributes                         | Member of 
--------------------+------------------------------------------------------------+-----------
 pg1                | Superuser, Create role, Create DB, Replication, Bypass RLS | {}
 postgres           | Superuser                                                  | {}
 postgres_exporter  |                                                            | {}
 postgres_exporter1 |                                                            | {}
 zsk                |                                                            | {}
test-# \dg+
                                               List of roles
     Role name      |                         Attributes                         | Member of | Description 
--------------------+------------------------------------------------------------+-----------+-------------
 pg1                | Superuser, Create role, Create DB, Replication, Bypass RLS | {}        | 
 postgres           | Superuser                                                  | {}        | 
 postgres_exporter  |                                                            | {}        | 
 postgres_exporter1 |                                                            | {}        | 
 zsk                |                                                            | {}        | 

查询当前数据库下有哪些schema:

test-# \dn
  List of schemas
  Name  |  Owner   
--------+----------
 mytest | postgres
 public | pg1
(2 rows)
test-# \dn+
                        List of schemas
  Name  |  Owner   | Access privileges |      Description       
--------+----------+-------------------+------------------------
 mytest | postgres |                   | 
 public | pg1      | pg1=UC/pg1       +| standard public schema
        |          | =UC/pg1           | 
(2 rows)

查询函数的定义(不是很准确,只是个大概的函数定义内容):

test-# \sf copytable 
CREATE OR REPLACE FUNCTION public.copytable(new_table_name character varying, old_table_name character varying, times integer)
 RETURNS integer
 LANGUAGE plpgsql
AS $function$
DECLARE
   stmt1 varchar(1000);
   stmt2 varchar(1000);
begin
   for i in 1..times loop
       raise notice '当前次数%',i;
       stmt1 := format('create table "%1$s_%3$s" (like "%2$s" INCLUDING INDEXES INCLUDING DEFAULTS INCLUDING COMMENTS);',new_table_name,old_table_name,i);
       stmt2 := format('insert into "%1$s_%3$s" select * from "%2$s" ;',new_table_name,old_table_name,i);
       raise notice '%',stmt1;
       raise notice '%',stmt2;
       EXECUTE format('drop table if EXISTS "%1$s_%3$s";',new_table_name,old_table_name,i) ;
       EXECUTE stmt1 ;
       EXECUTE stmt2 ;
   end loop;
   return 110;      
END; $function$

查询视图的定义:

test=# create view emp_view as select empno,ename from emp;
CREATE VIEW
test=# \sv emp_view 
CREATE OR REPLACE VIEW public.emp_view AS
 SELECT emp.empno,
    emp.ename
   FROM emp

四,

timing SQL语句执行计时

postgres=# \timing on
Timing is on.
postgres=# \timing off
Timing is off.

set 快速设置数据库内的变量,例如关闭自动提交,如果没有使用参数,就打印所有变量:

postgres=# \set AUTOCOMMIT Off

执行shell命令,某些时候不需要切出命令行,比较方便

postgres=# \! ls ~/
1111.sh    auto-sql.sh  database-test.dump  ewrwer.txt  myglobals.sql  test-backup     test-database.sql  test.tar.gz
12345.txt  backup_log emp-bak1.sql      logs  SQL 
相关实践学习
使用PolarDB和ECS搭建门户网站
本场景主要介绍基于PolarDB和ECS实现搭建门户网站。
阿里云数据库产品家族及特性
阿里云智能数据库产品团队一直致力于不断健全产品体系,提升产品性能,打磨产品功能,从而帮助客户实现更加极致的弹性能力、具备更强的扩展能力、并利用云设施进一步降低企业成本。以云原生+分布式为核心技术抓手,打造以自研的在线事务型(OLTP)数据库Polar DB和在线分析型(OLAP)数据库Analytic DB为代表的新一代企业级云原生数据库产品体系, 结合NoSQL数据库、数据库生态工具、云原生智能化数据库管控平台,为阿里巴巴经济体以及各个行业的企业客户和开发者提供从公共云到混合云再到私有云的完整解决方案,提供基于云基础设施进行数据从处理、到存储、再到计算与分析的一体化解决方案。本节课带你了解阿里云数据库产品家族及特性。
目录
相关文章
|
5天前
|
关系型数据库 数据库 PostgreSQL
PostgreSQL数据库的字符串拼接语法使用说明
【6月更文挑战第11天】PostgreSQL数据库的字符串拼接语法使用说明
15 1
|
6天前
|
SQL 关系型数据库 数据库
Python查询PostgreSQL数据库
木头左教你如何用Python连接PostgreSQL数据库:安装`psycopg2`库,建立连接,执行SQL脚本如创建表、插入数据,同时掌握错误处理和事务管理。别忘了性能优化,利用索引、批量操作提升效率。下期更精彩!💡 csvfile
Python查询PostgreSQL数据库
|
6天前
|
SQL 关系型数据库 数据库
Python执行PostgreSQL数据库查询语句,并打印查询结果
本文介绍了如何使用Python连接和查询PostgreSQL数据库。首先,确保安装了`psycopg2`库,然后创建数据库连接函数。接着,展示如何编写SQL查询并执行,例如从`employees`表中选取所有记录。此外,还讨论了处理查询结果、格式化输出和异常处理的方法。最后,提到了参数化查询和事务处理以增强安全性及确保数据一致性。
Python执行PostgreSQL数据库查询语句,并打印查询结果
|
7天前
|
SQL Oracle 关系型数据库
探索 Linux 命令 `db_archive`:Oracle 数据库归档日志的工具
探索 Linux 中的 `db_archive`,实际与 Oracle 数据库归档日志管理相关。在 Oracle 中,归档日志用于恢复,当在线重做日志满时自动归档。管理员可使用 SQL*Plus 查看归档模式,通过 `RMAN` 进行备份和恢复操作。管理归档日志需谨慎,避免数据丢失。了解归档管理对 Oracle 管理员至关重要,确保故障时能快速恢复数据库。
|
7天前
|
数据可视化 Linux 数据库
探索 Linux 命令 `db_tuner`:优化数据库性能的利器
`db_tuner` 是一个假设的 Linux 工具,用于数据库性能优化,提供状态检查、查询分析、配置调优、索引建议及报告生成等功能。虽然不是真实命令,但类似工具如 `mysqltuner` 可实现这些功能。通过安装和运行 `db_tuner`,DBA 可以提升数据库性能,解决瓶颈问题。
|
7天前
|
Oracle 关系型数据库 MySQL
深入了解 Linux 命令 `db_stat`:数据库统计信息的获取
本文模拟了 Linux 环境下使用 `db_stat` 命令获取数据库统计信息的场景,实际上`db_stat`是特定数据库系统的自定义工具。文章通过示例展示了如何针对Oracle、PostgreSQL和MySQL使用各自内置命令收集统计信息,强调了权限、性能影响和数据实时性等因素,并指出这些信息对优化数据库管理至关重要。
|
7天前
|
存储 缓存 Linux
深入理解Linux中的`db_load`命令:数据库加载的利器
`db_load`是Linux下处理Berkeley DB的关键命令,用于将文本数据加载到数据库中。它支持多种文本格式,如键值对和CSV,并具有灵活的选项,如指定数据库类型、缓存大小、日志记录和错误处理。通过`-f`加载文本文件,`-s`设定数据库类型,`-l`设置缓存。本文详细介绍了`db_load`的使用方法和高级特性,并给出案例,如将CSV用户信息加载到Btree数据库。了解并善用`db_load`能提升数据处理效率和安全性。
|
7天前
|
存储 安全 Linux
使用 `db_dump` 命令备份 Berkeley DB 数据库
`db_dump` 是 Linux 中用于备份 Berkeley DB 数据库的工具,它将数据库内容转储到输出或文件。
|
9天前
|
关系型数据库 数据库连接 分布式数据库
PolarDB操作报错合集之数据库访问量低时,可以正常连接数据库,访问量高了所有用户都连接不了数据库,为什么
PolarDB是阿里云推出的一种云原生数据库服务,专为云设计,提供兼容MySQL、PostgreSQL的高性能、低成本、弹性可扩展的数据库解决方案,可以有效地管理和优化PolarDB实例,确保数据库服务的稳定、高效运行。以下是使用PolarDB产品的一些建议和最佳实践合集。
|
9天前
|
SQL 关系型数据库 MySQL
MySQL数据库——概述-MySQL的安装、启动与停止和客户端连接、关系型数据库(RDBMS)、数据模型
MySQL数据库——概述-MySQL的安装、启动与停止和客户端连接、关系型数据库(RDBMS)、数据模型
28 0

热门文章

最新文章