PostgreSQL自带的命令行工具--psql

编者按:

PostgreSQL好火啊,不学点儿PG都不好意思说自己是数据库从业者。


【免责声明】本公众号文章仅代表个人观点,与任何公司无关,仅供参考。


编辑|SQL和数据库技术(ID:SQLplusDB)

和Oracle的sqlplus、MySQL自带命令行类似。psql是PostgreSQL自带的命令行工具,功能全面,是PostgreSQL数据库最重要的命令行工具之一。

通过psql工具可以和PostgreSQL数据库服务器进行SQL命令行交互。另外,psql工具也提供了大量强大的元命令(以反斜杠“\”开头的命令)。

使用psql连接数据库

    --连接数据库
    shell> psql -h <主机名> -p <端口号> -U <用户名> <数据库名>

    例:

      ubuntu@pg-vm:~$ psql -U postgres -d postgres -h localhost
      Password for user postgres:
      psql (12.12 (Ubuntu 12.12-0ubuntu0.20.04.1))
      SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, bits: 256, compression: off)
      Type "help" for help.


      postgres=#

      psql帮助内容

      可以通过在psql命令行键入help获得帮助内容。

        postgres=# help
        You are using psql, the command-line interface to PostgreSQL.
        Type: \copyright for distribution terms
        \h for help with SQL commands
        \? for help with psql commands
        \g or terminate with semicolon to execute query
        \q to quit

        \copyright  发布条款

          postgres=# \copyright
          PostgreSQL Database Management System
          (formerly known as Postgres, then as Postgres95)


          Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group


          Portions Copyright (c) 1994, The Regents of the University of California


          Permission to use, copy, modify, and distribute this software and its
          documentation for any purpose, without fee, and without a written agreement
          is hereby granted, provided that the above copyright notice and this
          paragraph and the following two paragraphs appear in all copies.


          IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
          DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING
          LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
          DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE
          POSSIBILITY OF SUCH DAMAGE.


          THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
          INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
          AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
          ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO
          PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.


          \h SQL命令的帮助

          \h获取所有的SQL命令。

            postgres=# \h


            Available help:
            ABORT CREATE FOREIGN DATA WRAPPER DROP ROUTINE
            ALTER AGGREGATE CREATE FOREIGN TABLE DROP RULE
            ALTER COLLATION CREATE FUNCTION DROP SCHEMA
            ALTER CONVERSION CREATE GROUP DROP SEQUENCE
            ALTER DATABASE CREATE INDEX DROP SERVER
            ALTER DEFAULT PRIVILEGES CREATE LANGUAGE DROP STATISTICS
            ALTER DOMAIN CREATE MATERIALIZED VIEW DROP SUBSCRIPTION
            ALTER EVENT TRIGGER CREATE OPERATOR DROP TABLE
            ALTER EXTENSION CREATE OPERATOR CLASS DROP TABLESPACE
            ALTER FOREIGN DATA WRAPPER CREATE OPERATOR FAMILY DROP TEXT SEARCH CONFIGURATION
            ALTER FOREIGN TABLE CREATE POLICY DROP TEXT SEARCH DICTIONARY
            ALTER FUNCTION CREATE PROCEDURE DROP TEXT SEARCH PARSER
            ALTER GROUP CREATE PUBLICATION DROP TEXT SEARCH TEMPLATE
            ALTER INDEX CREATE ROLE DROP TRANSFORM
            ALTER LANGUAGE CREATE RULE DROP TRIGGER
            ALTER LARGE OBJECT CREATE SCHEMA DROP TYPE
            ALTER MATERIALIZED VIEW CREATE SEQUENCE DROP USER
            ALTER OPERATOR CREATE SERVER DROP USER MAPPING
            ALTER OPERATOR CLASS CREATE STATISTICS DROP VIEW
            ALTER OPERATOR FAMILY CREATE SUBSCRIPTION END
            ALTER POLICY CREATE TABLE EXECUTE
            ALTER PROCEDURE CREATE TABLE AS EXPLAIN
            ALTER PUBLICATION CREATE TABLESPACE FETCH
            ALTER ROLE CREATE TEXT SEARCH CONFIGURATION GRANT
            ALTER ROUTINE CREATE TEXT SEARCH DICTIONARY IMPORT FOREIGN SCHEMA
            ALTER RULE CREATE TEXT SEARCH PARSER INSERT
            ALTER SCHEMA CREATE TEXT SEARCH TEMPLATE LISTEN
            ALTER SEQUENCE CREATE TRANSFORM LOAD
            ALTER LANGUAGE CREATE RULE DROP TRIGGER
            ALTER LARGE OBJECT CREATE SCHEMA DROP TYPE
            ALTER MATERIALIZED VIEW CREATE SEQUENCE DROP USER
            ALTER OPERATOR CREATE SERVER DROP USER MAPPING
            ALTER OPERATOR CLASS CREATE STATISTICS DROP VIEW
            ALTER OPERATOR FAMILY CREATE SUBSCRIPTION END
            ALTER POLICY CREATE TABLE EXECUTE
            ALTER PROCEDURE CREATE TABLE AS EXPLAIN
            ALTER PUBLICATION CREATE TABLESPACE FETCH
            ALTER ROLE CREATE TEXT SEARCH CONFIGURATION GRANT
            ALTER ROUTINE CREATE TEXT SEARCH DICTIONARY IMPORT FOREIGN SCHEMA
            ALTER RULE CREATE TEXT SEARCH PARSER INSERT
            ALTER SCHEMA CREATE TEXT SEARCH TEMPLATE LISTEN
            ALTER SEQUENCE CREATE TRANSFORM LOAD
            ALTER SERVER CREATE TRIGGER LOCK
            ALTER STATISTICS CREATE TYPE MOVE
            ALTER SUBSCRIPTION CREATE USER NOTIFY
            ALTER SYSTEM CREATE USER MAPPING PREPARE
            ALTER TABLE CREATE VIEW PREPARE TRANSACTION
            ALTER TABLESPACE DEALLOCATE REASSIGN OWNED
            ALTER TEXT SEARCH CONFIGURATION DECLARE REFRESH MATERIALIZED VIEW
            ALTER TEXT SEARCH DICTIONARY DELETE REINDEX
            ALTER TEXT SEARCH PARSER DISCARD RELEASE SAVEPOINT
            ALTER TEXT SEARCH TEMPLATE DO RESET
            ALTER TRIGGER DROP ACCESS METHOD REVOKE
            ALTER TYPE DROP AGGREGATE ROLLBACK
            ALTER USER DROP CAST ROLLBACK PREPARED
            ALTER USER MAPPING DROP COLLATION ROLLBACK TO SAVEPOINT
            ALTER VIEW DROP CONVERSION SAVEPOINT
            ALTER STATISTICS CREATE TYPE MOVE
            ALTER SUBSCRIPTION CREATE USER NOTIFY
            ALTER SYSTEM CREATE USER MAPPING PREPARE
            ALTER TABLE CREATE VIEW PREPARE TRANSACTION
            ALTER TABLESPACE DEALLOCATE REASSIGN OWNED
            ALTER TEXT SEARCH CONFIGURATION DECLARE REFRESH MATERIALIZED VIEW
            ALTER TEXT SEARCH DICTIONARY DELETE REINDEX
            ALTER TEXT SEARCH PARSER DISCARD RELEASE SAVEPOINT
            ALTER TEXT SEARCH TEMPLATE DO RESET
            ALTER TRIGGER DROP ACCESS METHOD REVOKE
            ALTER TYPE DROP AGGREGATE ROLLBACK
            ALTER USER DROP CAST ROLLBACK PREPARED
            ALTER USER MAPPING DROP COLLATION ROLLBACK TO SAVEPOINT
            ALTER VIEW DROP CONVERSION SAVEPOINT
            ANALYZE DROP DATABASE SECURITY LABEL
            BEGIN DROP DOMAIN SELECT
            CALL DROP EVENT TRIGGER SELECT INTO
            CHECKPOINT DROP EXTENSION SET
            CLOSE DROP FOREIGN DATA WRAPPER SET CONSTRAINTS
            CLUSTER DROP FOREIGN TABLE SET ROLE
            COMMENT DROP FUNCTION SET SESSION AUTHORIZATION
            COMMIT DROP GROUP SET TRANSACTION
            COMMIT PREPARED DROP INDEX SHOW
            COPY DROP LANGUAGE START TRANSACTION
            CREATE ACCESS METHOD DROP MATERIALIZED VIEW TABLE
            CREATE AGGREGATE DROP OPERATOR TRUNCATE
            CREATE CAST DROP OPERATOR CLASS UNLISTEN
            CREATE COLLATION DROP OPERATOR FAMILY UPDATE
            CREATE CONVERSION DROP OWNED VACUUM
            CREATE DATABASE DROP POLICY VALUES
            CREATE DOMAIN DROP PROCEDURE WITH
            CREATE EVENT TRIGGER DROP PUBLICATION
            CREATE EXTENSION DROP ROLE

            可以通过 \n + <SQL命令>获得SQL命令的帮助。

            例:

              postgres=# \h create database
              Command: CREATE DATABASE
              Description: create a new database
              Syntax:
              CREATE DATABASE name
              [ [ WITH ] [ OWNER [=] user_name ]
              [ TEMPLATE [=] template ]
              [ ENCODING [=] encoding ]
              [ LC_COLLATE [=] lc_collate ]
              [ LC_CTYPE [=] lc_ctype ]
              [ TABLESPACE [=] tablespace_name ]
              [ ALLOW_CONNECTIONS [=] allowconn ]
              [ CONNECTION LIMIT [=] connlimit ]
              [ IS_TEMPLATE [=] istemplate ] ]


              URL: https://www.postgresql.org/docs/12/sql-createdatabase.html

               \? 元命令帮助

                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
                \? 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
                \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
                \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
                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 "postgres")
                \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

                例1:列出所有的数据库

                  postgres=# \l
                  List of databases
                  Name | Owner | Encoding | Collate | Ctype | Access privileges
                  -----------+----------+----------+---------+---------+-----------------------
                  postgres | postgres | UTF8 | C.UTF-8 | C.UTF-8 |
                  template0 | postgres | UTF8 | C.UTF-8 | C.UTF-8 | =c/postgres +
                  | | | | | postgres=CTc/postgres
                  template1 | postgres | UTF8 | C.UTF-8 | C.UTF-8 | =c/postgres +
                  | | | | | postgres=CTc/postgres
                  (3 rows)

                  例2:列出所有的 schema

                    postgres=# \dn
                    List of schemas
                    Name | Owner
                    --------+----------
                    public | postgres
                    (1 row)


                    例3:列出所有的数据库用户和角色

                      postgres=# \du
                      List of roles
                      Role name | Attributes | Member of
                      -----------+------------------------------------------------------------+-----------
                      postgres | Superuser, Create role, Create DB, Replication, Bypass RLS | {}


                      postgres=# \dg
                      List of roles
                      Role name | Attributes | Member of
                      -----------+------------------------------------------------------------+-----------
                      postgres | Superuser, Create role, Create DB, Replication, Bypass RLS | {}

                      psql元命令实际执行SQL

                      可以通过使用“\set ECHO_HIDDEN on |off"命令来显示元命令实际执行SQL。

                      例:

                        postgres-# \set ECHO_HIDDEN on
                        postgres-# \l
                        ********* QUERY **********
                        SELECT d.datname as "Name",
                        pg_catalog.pg_get_userbyid(d.datdba) as "Owner",
                        pg_catalog.pg_encoding_to_char(d.encoding) as "Encoding",
                        d.datcollate as "Collate",
                        d.datctype as "Ctype",
                        pg_catalog.array_to_string(d.datacl, E'\n') AS "Access privileges"
                        FROM pg_catalog.pg_database d
                        ORDER BY 1;
                        **************************


                        List of databases
                        Name | Owner | Encoding | Collate | Ctype | Access privileges
                        -----------+----------+----------+---------+---------+-----------------------
                        postgres | postgres | UTF8 | C.UTF-8 | C.UTF-8 |
                        template0 | postgres | UTF8 | C.UTF-8 | C.UTF-8 | =c/postgres +
                        | | | | | postgres=CTc/postgres
                        template1 | postgres | UTF8 | C.UTF-8 | C.UTF-8 | =c/postgres +
                        | | | | | postgres=CTc/postgres
                        (3 rows)

                        部分中文说明

                          命令  说明
                          \h help \h create table
                          \d tb_name 查看表(视图,索引,序列)结构
                          \du 查看用户列表
                          \dt 查询数据库所有表(非系统表)
                          \dS 列出系统表和索引
                          \di index_name 只查看指定索引
                          \df 列出函数
                          \dv 只显示视图
                          \ds 只显示序列
                          \dn 列出所有的schema
                          \db 显示所有的表空间
                          \dg 列出数据库的所有角色或用户
                          \dp或者\z 查看表的分配权限
                          \c [user_name] [db_name] 切换某用户到指定数据库
                          \timing on/off 显示执行sql的时间
                          \encoding encode_type 设置客户端编码
                          \pset [option [value] ] 输出格式设置
                          \l 显示所有数据库列表
                          \q 退出
                          \o filename 文本输出执行结果
                          \I filename 用于执行存储在外部文件的sql语句或命令
                          \x 数据按列展示,类似mysql的\G
                          自动补全:连续单击两次tab键


                          +:对比显示更加详细的信息,例如:\du+ \dt+ \d+
                          ?/* :查询匹配通配符,例如:\d tb?
                          pgsql -E :可以显示命令执行的对应的SQL语句


                          \pset边框设置
                          \pset boder 0 :不带任何边框
                          \pset boder 1 :输出内容有边框
                          \pset boder 2 :带边框


                          \pset设置文本输出格式
                          \pset format unaligned (默认分隔符|)
                          \pset filesep '分隔符' (例如:\t)

                          参考

                            http://www.postgres.cn/docs/12/app-psql.html
                            https://www.postgresql.org/docs/14/app-psql.html
                                   

                            免责声明:

                            1、本站资源由自动抓取工具收集整理于网络。

                            2、本站不承担由于内容的合法性及真实性所引起的一切争议和法律责任。

                            3、电子书、小说等仅供网友预览使用,书籍版权归作者或出版社所有。

                            4、如作者、出版社认为资源涉及侵权,请联系本站,本站将在收到通知书后尽快删除您认为侵权的作品。

                            5、如果您喜欢本资源,请您支持作者,购买正版内容。

                            6、资源失效,请下方留言,欢迎分享资源链接

                            文章评论

                            0条评论