- PostgreSQL 10 Administration Cookbook
- Simon Riggs Gianni Ciolli
- 291字
- 2021-06-25 22:03:50
How to do it…
The command that executes a single SQL command and prints the output is the easiest, as shown here:
$ psql -c "SELECT current_time"
timetz
-----------------
18:48:32.484+01
(1 row)
The -c command is non-interactive. If we want to execute multiple commands, we can write those commands in a text file and then execute them using the -f option. This command loads a very small and simple set of examples:
$ psql -f examples.sql
It produces the following output when successful:
SET
SET
SET
SET
SET
SET
DROP SCHEMA
CREATE SCHEMA
SET
SET
SET
CREATE TABLE
CREATE TABLE
COPY 5
COPY 3
The examples.sql script is very similar to a dump file produced by PostgreSQL backup tools, so this type of file and the output it produces are very common. When a command is executed successfully, PostgreSQL outputs a command tag equal to the name of that command; this is how the preceding output was produced.
The psql tool can also be used with both the -c and -f modes together; each one can be used multiple times. In this case, it will execute all the commands consecutively:
$ psql -c "SELECT current_time" –f examples.sql -c "SELECT current_time"
timetz
-----------------
18:52:15.287+01
(1 row)
...output removed for clarity...
timetz
-----------------
18:58:23.554+01
(1 row)
The psql tool can also be used in interactive mode, which is the default, so it requires no option:
$ psql
postgres=#
The first interactive command you'll need is the following:
postgres=# help
You can then enter SQL or other commands. The following is the last interactive command you'll need:
postgres=# \quit
Unfortunately, you cannot type quit on its own, nor can you type \exit, or other options. Sorry, just \quit, or \q for short!