database 如何从 bash shell 使用 psql 命令执行多个查询?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28803651/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to execute multiple queries using psql command from bash shell?
提问by Pankaj Goyal
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.
我需要使用 psql -c 命令从命令行执行 postgresql 查询。对于每个 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?
任何人都可以帮助我并告诉我正确的方法吗?
回答by keltar
-c
processes only one command. Without it however psql
expects commands to be passed into standard input, e.g.:
-c
只处理一个命令。但是没有它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
和管道。
回答by Clodoaldo Neto
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
所有输出都将发送到标准输出
回答by Salami
Using echo
and a pipe to fit it on a single line:
使用echo
和管道将其放在一条线上:
echo 'SELECT * FROM xyz_table; \n SELECT * FROM abc_table' | psql -U postgres
回答by Cyril Damm
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 “现在选择()” -c “选择版本()” -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 行)