如何从bash shell使用psql命令执行多个查询? [英] How to execute multiple queries using psql command from bash shell?

查看:394
本文介绍了如何从bash shell使用psql命令执行多个查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用psql -c命令从命令行执行PostgreSQL查询。
对于每个psql命令,它都会打开一个新的tcp连接以连接到数据库服务器并执行查询,这对于大量查询来说是一项开销。

I need to execute postgresql queries from command line using psql -c command. 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.

当前我可以这样执行单个查询:

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 仅处理一个命令。但是如果没有它, psql 期望将命令传递到标准输入中,例如:

-c processes only one command. Without it however psql expects commands to be passed into standard input, e.g.:

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

或者使用 echo 和管道。

这篇关于如何从bash shell使用psql命令执行多个查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆