简体   繁体   English

如何使用bash shell中的psql命令执行多个查询?

[英]How to execute multiple queries using psql command from bash shell?

I need to execute postgresql queries from command line using psql -c command. 我需要使用psql -c命令从命令行执行postgresql查询。 For every psql command, it opens a new tcp connection to connect to the database server and execute query which is a overhead for large number of queries. 对于每个psql命令,它会打开一个新的tcp连接以连接到数据库服务器并执行查询,这是大量查询的开销。

Currently I can execute single query like this: 目前我可以像这样执行单个查询:

psql -U postgres -h <ip_addr> -c "SELECT * FROM xyz_table;"

When I tried to execute multiple queries as below, but only the last query got executed. 当我尝试执行如下的多个查询,但只执行了最后一个查询。

psql -U postgres -h <ip_addr> -c "SELECT * FROM xyz_table; SELECT * FROM abc_table;"

Can anyone help me and tell me the proper way to do it? 任何人都可以帮助我并告诉我正确的方法吗?

-c processes only one command. -c只处理一个命令。 Without it however psql expects commands to be passed into standard input, eg: 没有它,但是psql期望命令被传递到标准输入,例如:

psql -U postgres -h <ip_addr> <database_name> << EOF
SELECT * FROM xyz_table;
SELECT * FROM abc_table;
EOF

Or by using echo and pipes. 或者使用echo和管道。

使用echo和管道将其安装在一条线上:

echo 'SELECT * FROM xyz_table; \n SELECT * FROM abc_table' | psql -U postgres 

The --file parameter executes a file's content --file参数执行文件的内容

psql -U postgres -h <ip_addr> -f "my_file.psql"

All the output will be sent to standard output 所有输出都将发送到标准输出

http://www.postgresql.org/docs/current/static/app-psql.html http://www.postgresql.org/docs/current/static/app-psql.html

at least from 9.6.2 this approach works as well: 至少从9.6.2开始,这种方法也适用:

psql -c "select now()" -c "select version()" -U postgres -h 127.0.0.1 psql -c“select now()” - c“select version()” - U postgres -h 127.0.0.1

now 现在

2017-12-26 20:25:45.874935+01 (1 row) 2017-12-26 20:25:45.874935 + 01(1排)

version

PostgreSQL 9.6.2 on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 5.3.1-14ubuntu2) 5.3.1 20160413, 64-bit (1 row) 在x86_64-pc-linux-gnu上的PostgreSQL 9.6.2,由gcc编译(Ubuntu 5.3.1-14ubuntu2)5.3.1 20160413,64位(1行)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM