Three ways to execute SQL scripts on the PostgreSQL database command line


foreword

In the production environment, database connection tools are often not provided for reasons such as security, so the update and upgrade of the database must be implemented through the command line. This article summarizes three ways to execute SQL scripts from the command line.

1. psql command execution

Command format:
psql [option...] [dbname] [username]
Introduction to common parameters:
-h: specify the IP address or host name.
-p: Specify the port, the default is 5432.
-U: Specifies the user name of the database.
-d: Specifies the database name.
-f: Specifies the file. Read commands from a file.

# 示例(ct.sql为sql脚本文件)
psql -d postgres -f /pgsql/postgresql/ct.sql

Use the above command to ensure that the ct.sql file is placed in a directory with permissions for the postgres account, otherwise a "Permission denied" error will be reported.
insert image description here
If your sql script is very short, you can also use the following method.

# 将sql语句放置在单引号中
psql -d postgres -c 'select version();'

insert image description here

Two, \i command execution

# 示例
\i /pgsql/postgresql/ct.sql

To use the above command, you need to enter the database with psql first, and ensure that the ct.sql file is placed in the directory with the permission of the postgres account, otherwise a "Permission denied" error will be reported.
insert image description here

Three, \e command execution

\e

After using the \e command and pressing Enter, the vi editor will appear, copy the sql script into the editor, and the script will be executed automatically after saving and exiting.
Enter \e and press Enter

to save and exit and execute the sql script automatically, as shown in the figure below.
insert image description here

Summarize

The three methods summarized above are relatively common and can be used flexibly according to your own application scenarios.

Guess you like

Origin blog.csdn.net/ma286388309/article/details/129088891