当前位置: 首页 > article >正文

PostgreSQL数据库自带的命令行工具--psql

文章目录

  • PostgreSQL自带的命令行工具--psql
    • 使用psql连接数据库
    • psql帮助内容
      • \copyright 发布条款
      • \h SQL命令的帮助
      • \? 元命令帮助
      • psql元命令实际执行SQL
      • 部分中文说明
      • 其他说明
    • 总结
    • 参考

【免责声明】文章仅供学习交流,观点代表个人,与任何公司无关。
编辑|SQL和数据库技术(ID:SQLplusDB)

PostgreSQL自带的命令行工具–psql

和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)

部分中文说明

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

其他说明

+:对比显示更加详细的信息,例如:\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)
自动补全:连续单击两次tab键

执行外部命令:在psql提示符下,使用“!”命令执行外部命令。例如,“! ls”将列出当前目录中的所有文件。

总结

在本文中介绍了PostgreSQL数据库自带的命令行工具–psql的主要特点和使用方法。

参考

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


http://www.kler.cn/news/18279.html

相关文章:

  • Lumerical------S 参数文件格式
  • Qt 制作小程序登录系统(超详细)
  • 浅谈 LRU
  • Web2与Web3开发的不同之处
  • python正则表达式
  • 第二章 Vim编辑器与Shell命令脚本
  • 双线性插值(Bilinear interpolation)原理推导
  • PyQGIS中一次性加载多个shp文件
  • 探索语音识别技术:从自动翻译到智能客服
  • electron打包运行白屏、Can not find modules ‘xxx‘,Dynamic Linking Error
  • JavaWeb ( 六 ) JSP
  • C# 判断文件/目录是否存在
  • AWS VPC 配置指南:快速创建和设置你的虚拟私有云
  • 【C++】map和set的介绍+使用
  • EC6110-Hi3798MV310-当贝纯净桌面-卡刷强刷固件包
  • 在 node.js 里面写 MySQL 增删改查语句
  • helm部署nacos
  • 线性结构-数组
  • nestjs笔记
  • 打动人心的故事 | 如何利用文案在Facebook上塑造品牌形象
  • 面试整理 - 二叉排序树 c语言 及java 例子
  • 【在homeassistant的ONVIF中配置TP-Link】
  • SpringBoot启用web模拟测试(一)
  • 固态继电器的优点
  • 增强型PID-自适应-前馈-神经网络控制研究(Matlab代码实现)
  • 网页端操作提示「msg.js」库简介
  • linux实现CP指令
  • LeetCode 2432. 处理用时最长的那个任务的员工
  • 从爆火的“哇呀挖”,思考我软件开发的人生意义何在?
  • JDK17新特性之--JDK9到JDK17 String 新增的新方法