第二章 psql客户端工具

pgAdmin是一款功能丰富、开源免费的PostgreSQL图形化工具。psql是PostgreSQL自带的命令行工具,功能全面,是PostgreSQL数据库工程师必须熟练掌握的命令行工具之一。
    pgAdmin的下载网址是:https://www.pgadmin.org/download/

2.2 pgsql功能及应用

psql是PostgreSQL自带的命令行客户端工具,具有丰富的功能,类似于Oracle命令行客户端工具sqlplus,这一节将介绍psql常用的功能和少数特殊功能。
    熟练掌握psql能便捷处理PostgreSQL日常维护工作。

2.2.1 使用psql连接数据库

用psql连接数据库非常简单,可以在数据库服务端执行,也可以远程连接数据库,在数据库服务端连接本地数据库实例所示:

  1. [postgres@fudao_db_cluster_003 ~]$ cat ~/.bash_profile
  2. # .bash_profile
  3.  
  4. # Get the aliases and functions
  5. if [ -f ~/.bashrc ]; then
  6. . ~/.bashrc
  7. fi
  8.  
  9. # User specific environment and startup programs
  10.  
  11. PATH=$PATH:$HOME/bin:/opt/pgsql/bin
  12.  
  13. export PATH
  14. [postgres@fudao_db_cluster_003 ~]$
  15. [postgres@fudao_db_cluster_003 ~]$ psql postgres postgres
  16. psql (10.0)
  17. Type "help" for help.
  18.  
  19. postgres=#

psql后面的第一个postgres表示库名,第二个postgres表示用户名,端口号默认使用变量$PGPORT配置的数据库端口号,这里是1921端口,为了后续演示方便,创建一个测试库mydb,
    归属为用户mydb库分配一个新表空间tbs_mydb,如下所示:

  1. -- 创建用户
  2. postgres=# CREATE ROLE pguser WITH ENCRYPTED PASSWORD 'pguser';
  3. CREATE ROLE
  4.  
  5. -- 创建表空间目录
  6. [postgres@fudao_db_cluster_003 ~]$ mkdir -p /data01/pgdata/10/pg_tbs/tbs_mydb
  7.  
  8. -- 创建表空间
  9. postgres=# CREATE TABLESPACE tbs_mydb OWNER pguser LOCATION '/data01/pgdata/10/pg_tbs/tbs_mydb';
  10. CREATE TABLESPACE
  11.  
  12. -- 创建数据库
  13. CREATE DATABASE mydb
  14. WITH OWNER = pguser
  15. TEMPLATE = template0
  16. ENCODING = 'UTF8'
  17. TABLESPACE = 'tbs_mydb';
  18. -- 赋权
  19. GRANT ALL ON DATABASE mydb TO pguser WITH GRANT OPTION;
  20. GRANT ALL ON TABLESPACE tbs_mydb TO pguser;
  21.  
  22. -- 查看角色
  23. postgres=# select rolname from pg_roles;
  24. rolname
  25. ----------------------
  26. pg_monitor
  27. pg_read_all_settings
  28. pg_read_all_stats
  29. pg_stat_scan_tables
  30. pg_signal_backend
  31. postgres
  32. pguser
  33. (7 rows)
  34.  
  35. postgres=# \du
  36. List of roles
  37. Role name | Attributes | Member of
  38. -----------+------------------------------------------------------------+-----------
  39. pguser | Cannot login | {}
  40. postgres | Superuser, Create role, Create DB, Replication, Bypass RLS | {}
  41.  
  42. postgres=#
  43.  
  44. 授权登录
  45. postgres=# alter role pguser login;
  46. ALTER ROLE
  47. postgres=# \du

CREATE DATABASE 命令中的OWNER选项表示数据库属主,TEMPLATE表示数据库模板,默认有template0和template1模板,也能自定义数据库模板,ENCODING表示数据库字符集,
    这里设置成UTF8,TABLESPACE 表示数据库的默认表空间,新建数据库对象将默认创建在此表空间上,通过psql远程连接数据库的语法如下:
    psql [option...] [dbname] [username]
    服务器pghost1的IP为10.192.30.60, pghost2的IP为10.192.30.59,在pghost2主机上远程连接pghost1的mydb的命令如下:

  1. [postgres@fudao_db_cluster_002 ~]$ psql -h pghost1 -p 1921 mydb pguser
  2. Password for user pguser:
  3. psql (10.0)
  4. Type "help" for help.
  5.  
  6. mydb=>

2.2.2 psql元命令介绍

pgsql中的元命令是指以反斜杠开头的命令,psql提供丰富的元命令,能够便捷地管理数据库,比如查看数据库对象定义、查看数据库对象占用空间大小,列出
    数据库各种对象名称、数据导入导出等,比如查看数据库列表,如下所示:

  1. [postgres@fudao_db_cluster_002 ~]$ psql -h pghost1 -p 1921 mydb pguser
  2. psql (10.0)
  3. Type "help" for help.
  4.  
  5. mydb=> \l
  6. List of databases
  7. Name | Owner | Encoding | Collate | Ctype | Access privileges
  8. -----------+----------+----------+-------------+-------------+-----------------------
  9. mydb | pguser | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =Tc/pguser +
  10. | | | | | pguser=C*T*c*/pguser
  11. postgres | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
  12. template0 | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/postgres +
  13. | | | | | postgres=CTc/postgres
  14. template1 | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/postgres +
  15. | | | | | postgres=CTc/postgres
  16. (4 rows)
  17.  
  18. mydb=>
  19.  
  20. 1. \db查看表空间列表
  21. mydb=> \db
  22. List of tablespaces
  23. Name | Owner | Location
  24. ------------+----------+-----------------------------------
  25. pg_default | postgres |
  26. pg_global | postgres |
  27. tbs_mydb | pguser | /data01/pgdata/10/pg_tbs/tbs_mydb
  28. (3 rows)
  29.  
  30. mydb=>

2. \d查看表定义
先创建一张测试表,如下所示:

  1. mydb=> CREATE TABLE test_1(id int4, name text, create_time timestamp without time zone default clock_timestamp());
  2. CREATE TABLE
  3. mydb=> ALTER TABLE test_1 ADD PRIMARY KEY (id);
  4. ALTER TABLE
  5.  
  6. generate_series函数产生连续的整数,使用这个函数能非常方便地产生测试数据,查看表test_1定义只需要执行元命令\d后接表名,如下所示:
  7. postgres=# \d test_1
  8. Table "public.test_1"
  9. Column | Type | Collation | Nullable | Default
  10. -------------+-----------------------------+-----------+----------+-------------------
  11. id | integer | | not null |
  12. name | text | | |
  13. create_time | timestamp without time zone | | | clock_timestamp()
  14. Indexes:
  15. "test_1_pkey" PRIMARY KEY, btree (id)
  16.  
  17. mydb=>

3. 查看表、索引占用空间大小
给测试表test_1插入500w数据,如下所示:

  1. mydb=> insert into test_1(id,name) select n,n || '_francs' from generate_series(1,5000000) n;
  2. 2019-06-26 16:29:47.498 CST [] LOG: checkpoints are occurring too frequently (25 seconds apart)
  3. 2019-06-26 16:29:47.498 CST [] HINT: Consider increasing the configuration parameter "max_wal_size".
  4. INSERT 0 5000000
  5. mydb=>
  6.  
  7. 查看表大小执行\dt+ 后接表名,如下所示:
  8. mydb=> \dt+ test_1
  9. List of relations
  10. Schema | Name | Type | Owner | Size | Description
  11. --------+--------+-------+--------+--------+-------------
  12. public | test_1 | table | pguser | 287 MB |
  13. (1 row)
  14.  
  15. 查看索引大小执行\di+ 后接索引名,如下所示:
  16. mydb=> \di+ test_1_pkey
  17. List of relations
  18. Schema | Name | Type | Owner | Table | Size | Description
  19. --------+-------------+-------+--------+--------+--------+-------------
  20. public | test_1_pkey | index | pguser | test_1 | 107 MB |
  21. (1 row)

4. \sf 查看函数代码
5. \x 设置查询结果输出

  1. mydb=> select * from test_1 limit 1;
  2. id | name | create_time
  3. ----+----------+----------------------------
  4. 1 | 1_francs | 2019-06-26 16:32:36.100912
  5. (1 row)
  6.  
  7. mydb=> \x
  8. Expanded display is on.
  9. mydb=> select * from test_1 limit 1;
  10. -[ RECORD 1 ]---------------------------
  11. id | 1
  12. name | 1_francs
  13. create_time | 2019-06-26 16:32:36.100912
  14.  
  15. mydb=>

6. 获取元数据对应的SQL代码
    psql提供的元命令实质上向数据库发出相应的SQL查看,当使用psql连接数据库时,-E选项可以获取元命令的SQL代码,如下所示:

  1. [postgres@fudao_db_cluster_002 ~]$ psql -h pghost1 -p 1921 mydb pguser -E
  2. Password for user pguser:
  3. psql (10.0)
  4. Type "help" for help.
  5.  
  6. mydb=> \db
  7. ********* QUERY **********
  8. SELECT spcname AS "Name",
  9. pg_catalog.pg_get_userbyid(spcowner) AS "Owner",
  10. pg_catalog.pg_tablespace_location(oid) AS "Location"
  11. FROM pg_catalog.pg_tablespace
  12. ORDER BY 1;
  13. **************************
  14.  
  15. List of tablespaces
  16. Name | Owner | Location
  17. ------------+----------+-----------------------------------
  18. pg_default | postgres |
  19. pg_global | postgres |
  20. tbs_mydb | pguser | /data01/pgdata/10/pg_tbs/tbs_mydb
  21. (3 rows)
  22.  
  23. mydb=>

7. \?
    PostgreSQL支持的元命令很多,当忘记具体的元命令名称时,可以查询手册,另一种便捷的方式是执行\?元命令列出所有的元命令,如下所示:

  1. mydb=> \?
  2. General
  3. \copyright show PostgreSQL usage and distribution terms
  4. \crosstabview [COLUMNS] execute query and display results in crosstab
  5. \errverbose show most recent error message at maximum verbosity
  6. \g [FILE] or ; execute query (and send results to file or |pipe)
  7. \gexec execute query, then execute each value in its result
  8. \gset [PREFIX] execute query and store results in psql variables
  9. \gx [FILE] as \g, but forces expanded output mode
  10. \q quit psql
  11. \watch [SEC] execute query every SEC seconds
  12.  
  13. Help
  14. \? [commands] show help on backslash commands
  15. \? options show help on psql command-line options
  16. \? variables show help on special variables
  17. \h [NAME] help on syntax of SQL commands, * for all commands
  18. ......

8. 便捷的HELP命令
    psql的HELP命令非常方便,使用元命令\h后接SQL命令关键字能将SQL的语法列出,对日常的数据库管理工作带来极大的便利,例如:

  1. mydb=> \h create tablespace
  2. Command: CREATE TABLESPACE
  3. Description: define a new tablespace
  4. Syntax:
  5. CREATE TABLESPACE tablespace_name
  6. [ OWNER { new_owner | CURRENT_USER | SESSION_USER } ]
  7. LOCATION 'directory'
  8. [ WITH ( tablespace_option = value [, ... ] ) ]
  9.  
  10. mydb=>

2.2.3 psql导入、导出表数据

psql支持文件数据导入到数据,也支持数据表数据导出到文件中。COPY命令和\copy命令都支持这两类操作,但两者有如下区别:
1) COPY命令是SQL命令,\copy是元命令;
2) COPY命令必须具有SUPERUSER超级权限(将数据通过stdin、stuout方式导入导出情况外),而\copy元命令不需要SUPERUSER权限。
3) COPY命令读取或写入数据库服务端主机上的文件,而\copy元命令是从psql客户端主机上写入文件。
4) 从性能方面看,大数据量导出到文件或大文件数据导入数据库,COPY比、copy性能高。

 1. 使用COPY命令导入导出数据
    先来看看COPY命令如何将文件数据导入到数据表中,首先在mydb中创建测试表 test_copy,如下:

  1. [postgres@fudao_db_cluster_002 ~]$ psql -h 10.192.30.60 -p 1921 -U pguser -W -d mydb
  2. Password for user pguser:
  3. psql (10.0)
  4. Type "help" for help.
  5.  
  6. mydb=> \d
  7. List of relations
  8. Schema | Name | Type | Owner
  9. --------+--------+-------+--------
  10. public | test_1 | table | pguser
  11. (1 row)
  12.  
  13. mydb=> CREATE TABLE test_copy(id int4, name text);
  14. CREATE TABLE
  15. mydb=>

之后编写数据文件test_copy_in.txt,字段分隔符用TAB键,也可以设置其他分隔符,导入时再指定设置的字段分隔符。test_copy_in.txt文件如下所示:

  1. [postgres@fudao_db_cluster_003 ~]$ cat /home/postgres/test_copy_in.txt
  2. 1,a
  3. 2,b
  4. 3,c
    [postgres@fudao_db_cluster_002 ~]$

之后以postgres用户登录mydb库,并将test_copy_in.txt文件中的数据导入到test_copy表中。导入命令如下:

  1. [postgres@fudao_db_cluster_002 ~]$ psql -h 10.192.30.60 -p 1921 -d mydb -U postgres
  2. Password for user postgres:
  3. psql (10.0)
  4. Type "help" for help.
  5.  
  6. mydb=# copy public.test_copy from '/home/postgres/test_copy_in.txt' with csv;
  7. COPY 3
  8. mydb=# select * from test_copy;
  9. id | name
  10. ----+------
  11. 1 | a
  12. 2 | b
  13. 3 | c
  14. (3 rows)

# 使用普通用户

  1. [postgres@fudao_db_cluster_002 ~]$ psql -h 10.192.30.60 mydb pguser
  2. Password for user pguser:
  3. psql (10.0)
  4. Type "help" for help.
  5.  
  6. mydb=> copy public.test_copy from '/home/postgres/test_cpoy_in.txt';
  7. ERROR: must be superuser to COPY to or from a file
  8. HINT: Anyone can COPY to stdout or from stdin. psql's \copy command also works for anyone.
  9. mydb=>

# 从远程登录看看

  1. [postgres@fudao_db_cluster_002 ~]$ cat /home/postgres/test_copy_in.txt
  2. 1,a
  3. 2,b
  4. 3,c
  5. 4,d
  6. [postgres@fudao_db_cluster_002 ~]$ psql -h 10.192.30.60 -p 1921 mydb pguser
  7. Password for user pguser:
  8. psql (10.0)
  9. Type "help" for help.
  10.  
  11. mydb=> \dt
  12. List of relations
  13. Schema | Name | Type | Owner
  14. --------+-----------+-------+--------
  15. public | test_1 | table | pguser
  16. public | test_copy | table | pguser
  17. (2 rows)
  18.  
  19. mydb=> select * from test_copy;
  20. id | name
  21. ----+------
  22. (0 rows)
  23.  
  24. mydb=> copy test_copy from '/home/postgres/test_copy_in.txt' with csv;
  25. ERROR: must be superuser to COPY to or from a file
  26. HINT: Anyone can COPY to stdout or from stdin. psql's \copy command also works for anyone.
  27. mydb=> \copy test_copy from '/home/postgres/test_copy_in.txt' with csv;
  28. COPY 4
  29. mydb=> select * from test_copy ;
  30. id | name
  31. ----+------
  32. 1 | a
  33. 2 | b
  34. 3 | c
  35. 4 | d
  36. (4 rows)

# 使用postgres用户远程登录,copy导出数据的文件,是在postgres数据的服务器端,不在客户端机器上

  1. [postgres@fudao_db_cluster_002 ~]$ psql -h 10.192.30.60 -p 1921 mydb postgres
  2. Password for user postgres:
  3. psql (10.0)
  4. Type "help" for help.
  5.  
  6. mydb=# \dt
  7. List of relations
  8. Schema | Name | Type | Owner
  9. --------+-----------+-------+--------
  10. public | test_1 | table | pguser
  11. public | test_copy | table | pguser
  12. (2 rows)
  13.  
  14. mydb=# copy pguser.test_copy to '/tmp/test_copy_out.txt';
  15. ERROR: schema "pguser" does not exist
  16. mydb=# copy public.test_copy to '/tmp/test_copy_out.txt';
  17. COPY 4
  18. mydb=# \! cat /tmp/test_copy_out.txt
  19. cat: /tmp/test_copy_out.txt: No such file or directory
  20. mydb=#

# 使用非postgres用户登录,是在本地产生

  1. [postgres@fudao_db_cluster_002 ~]$ psql -h 10.192.30.60 -p 1921 mydb pguser
  2. Password for user pguser:
  3. psql (10.0)
  4. Type "help" for help.
  5.  
  6. mydb=> copy public.test_copy to '/tmp/test_copy_out.txt';
  7. ERROR: must be superuser to COPY to or from a file
  8. HINT: Anyone can COPY to stdout or from stdin. psql's \copy command also works for anyone.
  9. mydb=> \copy public.test_copy to '/tmp/test_copy_out.txt';
  10. COPY 4
  11. mydb=> \! cat /tmp/test_copy_out.txt
  12. 1 a
  13. 2 b
  14. 3 c
  15. 4 d
  16. mydb=>
  17. mydb=> truncate table test_copy
  18. mydb-> ;
  19. TRUNCATE TABLE
  20. mydb=> select * from test_copy ;
  21. id | name
  22. ----+------
  23. (0 rows)
  24.  
  25. mydb=> \copy test_copy from /tmp/test_copy_out.txt';
  26. ERROR: unterminated quoted string at or near "';"
  27. LINE 1: COPY test_copy FROM STDIN ';
  28. ^
  29. mydb=> \copy test_copy from '/tmp/test_copy_out.txt';
  30. COPY 4
  31. mydb=> select * from test_copy ;
  32. id | name
  33. ----+------
  34. 1 | a
  35. 2 | b
  36. 3 | c
  37. 4 | d
  38. (4 rows)
  39.  
  40. mydb=>

经常有运营或开发人员要求DBA提供生产库的运营数据,为了显示方便,这时需要将数据导出到csv格式。

  1. [postgres@fudao_db_cluster_002 ~]$ psql -h 10.192.30.60 -p 1921 mydb postgres
  2. Password for user postgres:
  3. psql (10.0)
  4. Type "help" for help.
  5.  
  6. mydb=# \dt
  7. List of relations
  8. Schema | Name | Type | Owner
  9. --------+-----------+-------+--------
  10. public | test_1 | table | pguser
  11. public | test_copy | table | pguser
  12. (2 rows)
  13.  
  14. mydb=# \copy public.test_copy to '/tmp/test_copy_out.csv' with csv header;
  15. COPY 4
  16. mydb=# \! cat '/tmp/test_copy_out.csv'
  17. id,name
  18. 1,a
  19. 2,b
  20. 3,c
  21. 4,d
  22. mydb=#

上述命令中的with scv header是指导出格式为csv格式并且显示字段名称,以csv为后缀名的文件可以使用office execl打开。以上数据导出示例
都是基于全表数据导出的,如何仅导出表的一部分数据呢?如下代码仅导出表test_copy中ID等于1的数据记录。

  1. mydb=# copy (select * from public.test_copy where id = 1) to '/tmp/1.txt';
  2. COPY 1
  3. mydb=# \! cat /tmp/1.txt
  4. 1 a
  5. mydb=#

2. 使用copy元命令导入导出数据
    COPY命令是从数据库服务端主机读取或写入文件数据,而\copy元命令从psql用客户端主机读取或写入文件数据。并且\copy元命令不需要超级用户权限。
下面在pghost2中以普通用户pguser远程登录pghost1主机上的mydb库,并且使用\copy元命令导出text_copy数据。如下:

  1. mydb=> \copy test_copy to '/tmp/2_test_copy.dump.txt';
  2. COPY 4
  3. mydb=> \! cat /tmp/2_test_copy.dump.txt
  4. 1 a
  5. 2 b
  6. 3 c
  7. 4 d
  8. mydb=>
  9.  
  10. [postgres@fudao_db_cluster_002 tmp]$ cat 3_test_copy.dump.txt
  11. 1 a
  12. 2 b
  13. 3 c
  14. 4 d
  15. 5 e
  16. 6 f
  17. 7 h
  18. [postgres@fudao_db_cluster_002 tmp]$
  19.  
  20. mydb=> select * from test_copy ;
  21. id | name
  22. ----+------
  23. 1 | a
  24. 2 | b
  25. 3 | c
  26. 4 | d
  27. (4 rows)
  28.  
  29. mydb=> \copy test_copy from '/tmp/3_test_copy.dump.txt';
  30. COPY 7
  31. mydb=>
  32. mydb=> select * from test_copy ;
  33. id | name
  34. ----+------
  35. 1 | a
  36. 2 | b
  37. 3 | c
  38. 4 | d
  39. 1 | a
  40. 2 | b
  41. 3 | c
  42. 4 | d
  43. 5 | e
  44. 6 | f
  45. 7 | h
  46. (11 rows)

没有超级用户权限的情况下,需要导出小表,通常使用\copy元命令。如果是大表导入导出,建议在数据库服务器端主机使用copy命令,效率更好

2.2.4 psql的语法和选项介绍

psql连接数据库语法如下:
    psql [OPTION]... [DBNAME [USERNAME]]
    其中dbname指连接的数据库名称,username指登录数据库的用户名,option有很多参数选项,这节列出重要的参数选项。
1. -A设置非对齐输出模式
psql执行SQL的输出默认是对齐模式,例如:

  1. [postgres@fudao_db_cluster_003 ~]$ psql -c "select * from test_copy where id=1" mydb pguser
  2. id | name
  3. ----+------
  4. 1 | a
  5. (1 row)
  6.  
  7. [postgres@fudao_db_cluster_003 ~]$

注意以上输出,格式是对齐的,psql加上-A选项如下:

  1. [postgres@fudao_db_cluster_003 ~]$ psql -A -c "select * from test_copy where id=1" mydb pguser
  2. id|name
  3. 1|a
  4. (1 row)
  5. [postgres@fudao_db_cluster_003 ~]$

加上-A选项后,以上输出的格式变成不对齐的了,并且返回结果中没有空行,接着看-t选项。
2. -t只显示记录数据
    另一个psql重要选项参数为-t,-t参数设置输出只显示数据,而不显示字段名称和返回的结果集行数,如下所示:

  1. [postgres@fudao_db_cluster_003 ~]$ psql -t -c "select * from test_copy where id=1" mydb pguser
  2. 1 | a
  3.  
  4. [postgres@fudao_db_cluster_003 ~]$

注意以上结果,字段名称不再显示,返回的结果行数也没有显示,但尾部仍然有空行,因此-t参数通常和-A参数结合使用,
这时金返回数据本身,如下所示:

  1. [postgres@fudao_db_cluster_003 ~]$ psql -At -c "select * from test_copy where id=1" mydb pguser
  2. 1|a
  3. [postgres@fudao_db_cluster_003 ~]$

以上结果进返回了数据本身,在编写shell脚本时非常有效,特别是只取一个字段的时候,如下所示:

  1. [postgres@fudao_db_cluster_003 ~]$ psql -At -c "select name from test_copy where id=1" mydb pguser
  2. a
  3. [postgres@fudao_db_cluster_003 ~]$

3. -q不显示输出信息
    默认情况下,使用psql执行SQL命令时会返回多种消息,使用-q参数后将不再显示这些信息,下面通过一个例子进行演示,首先创建 test_q.sql。
并输入一下SQL:

  1. [postgres@fudao_db_cluster_003 ~]$ psql mydb -f /tmp/test_q.sql
  2. DROP TABLE
  3. CREATE TABLE
  4. TRUNCATE TABLE
  5. INSERT 0 1
  6. INSERT 0 1
  7. [postgres@fudao_db_cluster_003 ~]$

执行脚本后,返回了一对消息,加上-q参数后,这些信息不再显示了。

  1. [postgres@fudao_db_cluster_003 ~]$ psql -q mydb -f /tmp/test_q.sql
  2. [postgres@fudao_db_cluster_003 ~]$

-q选项通常和-c或-f选项使用,在执行维护操作过程中,当输出信息不重要时,这个特性非常重要。

2.2.5 psql执行sql脚本

psql的-c选项支持在操作系统层面通过psql向数据库发起SQL命令,如下所示:

  1. [postgres@fudao_db_cluster_003 ~]$ psql -c "select * from test_copy" mydb
  2. id | name
  3. ----+------
  4. 1 | a
  5. 2 | b
  6. 3 | c
  7. 4 | d
  8. 5 | e
  9. 6 | f
  10. 7 | h
  11. (7 rows)
  12.  
  13. [postgres@fudao_db_cluster_003 ~]$

-c选项后接执行的SQL命令,可以使用单引号或者双引号,同时支持格式化输出,如果想仅仅显示命令返回的结果,psql加上-At选项即可。

  1. [postgres@fudao_db_cluster_003 ~]$ psql -At -c "select * from test_copy" mydb
  2. 1|a
  3. 2|b
  4. 3|c
  5. 4|d
  6. 5|e
  7. 6|f
  8. 7|h
  9. [postgres@fudao_db_cluster_003 ~]$

上述内容演示了在操作系统层面通过psql执行SQL命令,那么如何导入数据库脚文件了?首先编写一下文件,文件名称为test_1.sql

  1. [postgres@fudao_db_cluster_003 ~]$ cat /tmp/test_2.sql
  2. CREATE TABLE test_2(id int4);
  3. INSERT INTO test_2 VALUES(1);
  4. INSERT INTO test_2 VALUES(2);
  5. INSERT INTO test_2 VALUES(3);
  6. [postgres@fudao_db_cluster_003 ~]$

通过-f参数导入次脚本,命令如下:

  1. [postgres@fudao_db_cluster_003 ~]$ psql mydb pguser -f /tmp/test_2.sql
  2. CREATE TABLE
  3. INSERT 0 1
  4. INSERT 0 1
  5. INSERT 0 1
  6. [postgres@fudao_db_cluster_003 ~]$

以上命令的输出结果没有报错,表示文件中所有的SQL正常导入。psql的 --single-transaction或-l选项支持在一个事务中执行脚本,要么脚本中的所有
SQL执行成功,如果其中有SQL执行失败,则文件中的所有SQL。

2.2.6 psql如何传递变量到SQL

如何通过psql工具将变量传递到SQL中,例如以下SQL:
SELECT * FROM test_name WHERE clumn_name = '变量';

下面演示两种传递变量的方式。
1. \set 元命令方式传递变量
    \set 元子命令可以设置变量,格式如下:name表示变量名称,value表示变量值,如果不填写value,变量值为空。

  1. mydb=> \set v_id 2
  2. mydb=> select * from test_copy where id=:v_id;
  3. id | name
  4. ----+------
  5. 2 | b
  6. (1 row)

如果想取消之前的变量的值,\set 命令后跟参数名称即可。

  1. mydb=> \set v_id

通过\set 元命令设置变量的一个典型应用场景是使用pgbench进行压测时使用\set元命令为变量赋值。
2. psql的-v参数传递变量
    另一种方式是通过psql的-v参数传递变量,首先编写select_1.sql脚本,脚本内容如下:

  1. [postgres@fudao_db_cluster_003 ~]$ cat select_1.sql
  2. select * from test_copy where id=:v_id ;
  3. [postgres@fudao_db_cluster_003 ~]$
  4. [postgres@fudao_db_cluster_003 ~]$ psql mydb pguser -v v_id=1 -f /home/postgres/select_1.sql
  5. id | name
  6. ----+------
  7. 1 | a
  8. (1 row)
  9.  
  10. [postgres@fudao_db_cluster_003 ~]$
  11. 以上设置变量v_id值为1

第二章 psql客户端工具的更多相关文章

  1. 第二章 Qt常用工具的介绍

    第二章 Qt常用工具的介绍 (1)No.1 qmake 相信编写过Makefile的开发人员,随着工程中源码的级数递增和以类型.功能.模块组织源码的子目录的增多,都不愿意重复机械地手工编写这个工程管理 ...

  2. Android群英传》读书笔记 (1) 第一章 Android体系与系统架构 + 第二章 Android开发工具新接触

    第一章 Android体系与系统架构 1.Dalvik 和 ARTDalvik好比是一辆可折叠的自行车,平时是折叠的,只有骑的时候,才需要组装起来用.ART好比是一辆组装好了的自行车,装好就可以骑了. ...

  3. 第二章排错的工具:调试器Windbg(上)

    感谢博主 http://book.51cto.com/art/200711/59731.htm <Windows用户态程序高效排错>第二章主要介绍用户态调试相关的知识和工具.本文主要讲了排 ...

  4. 第二章排错的工具:调试器Windbg(下)

    感谢博主 http://book.51cto.com/art/200711/59874.htm 2.2  读懂机器的语言:汇编,CPU执行指令的最小单元2.2.1  需要用汇编来排错的常见情况 汇编是 ...

  5. 第四章· MySQL客户端工具及SQL讲解

    一.客户端命令介绍 1.mysql 1.用于数据库的连接管理 1) 连接(略) 2) 管理: #MySQL接口自带的命令 \h 或 help 或? 查看帮助 \G 格式化查看数据(key:value) ...

  6. 第二章 Mybatis代码生成工具

    1.mybatis-generator作用 1).生成pojo 与 数据库结构对应 2).如果有主键,能匹配主键 3).如果没有主键,可以用其他字段去匹配 4).动态select,update,del ...

  7. 【Dalston】【第二章】客户端负载均衡(Ribbon)

    对于大型应用系统负载均衡(LB:Load Balancing)是首要被解决一个问题.在微服务之前LB方案主要是集中式负载均衡方案,在服务消费者和服务提供者之间又一个独立的LB,LB通常是专门的硬件,如 ...

  8. 微信小程序教学第二章:小程序中级实战教程之预备篇 - 项目结构设计 |基于最新版1.0开发者工具

    iKcamp官网:http://www.ikcamp.com 访问官网更快阅读全部免费分享课程:<iKcamp出品|全网最新|微信小程序|基于最新版1.0开发者工具之初中级培训教程分享>. ...

  9. Android群英传笔记——第二章:Android开发工具新接触

    Android群英传笔记--第二章:Android开发工具新接触 其实这一章并没什么可讲的,前面的安装Android studio的我们可以直接跳过,如果有兴趣的,可以去看看Google主推-Andr ...

随机推荐

  1. unieap platform eclipse.ini vm设置

    -vm C:\Program Files (x86)\Java\jdk1..0_45\bin\javaw.exe -startup plugins/org.eclipse.equinox.launch ...

  2. PowerDesigner_15连接Oracle11g,反向工程导出模型图

    1.启动PowerDesigner2.菜单:File->ReverseEngineer->Database出来NewPhysicalDataModel对话框,DBMS选择ORACLEVer ...

  3. 关于img标签浏览器自带的边框,清除边框的解决方式(即img[src=""] img无路径情况下,灰色边框去除解决方法)

    详解img[src=""] img无路径情况下,灰色边框去除解决方法 1.Js解决办法 <html> <head> <meta charset=&qu ...

  4. centos7 忘记root密码,如何进入单用户模式。

    init方法 1.centos7的grub2界面会有两个入口,正常系统入口和救援模式: 2.修改grub2引导 在正常系统入口上按下"e",会进入edit模式,搜寻ro那一行,以l ...

  5. springboot mybatis下临时表的创建和删除,可用于查重去重

    /** * 创建临时表 */ @Update({"drop temporary table if exists ${tableName};", "create tempo ...

  6. PHP 按照时区获取当前时间

    /**  * 时间格式化  * @param string $dateformat 时间格式  * @param int $timestamp 时间戳  * @param int $timeoffse ...

  7. word2vec原理浅析

     1.word2vec简介 word2vec,即词向量,就是一个词用一个向量来表示.是2013年Google提出的.word2vec工具主要包含两个模型:跳字模型(skip-gram)和连续词袋模型( ...

  8. 20个python项目--图片转字符画

    转自实验楼:https://www.shiyanlou.com/courses/370/learning/?id=1191 代码: # -*- coding:utf-8 -*- from PIL im ...

  9. [Vuejs] 给ref赋值需要注意的问题

    1.简单赋值 <div ref="refCon"></div> 访问方式: this.$refs.refCon 2.循环赋值,相同名称 <div v- ...

  10. xmake从入门到精通9:交叉编译详解

    xmake是一个基于Lua的轻量级现代化c/c 的项目构建工具,主要特点是:语法简单易上手,提供更加可读的项目维护,实现跨平台行为一致的构建体验. 除了win, linux, macOS平台,以及an ...