我需要从bash / expect脚本执行以下sql查询 从bash脚本运行这些查询的首选方法是什么
# psql ambari -U ambari
Password for user ambari:
psql (9.2.24)
Type "help" for help.
ambari=>
ambari=>
ambari=>
ambari=> select
ambari-> sum(case when ulo = 1 then 1 else 0 end) as ulo_1,
ambari-> sum(case when ulo = 2 then 1 else 0 end) as ulo_2,
.
.
.
我们可以访问PostgreSQL
psql ambari -U ambari
Password for user ambari:bigdata
运行此命令时(/ tmp / file包含查询的bach)
psql -U ambari -f /tmp/file ambari
我们得到
psql: FATAL: no pg_hba.conf entry for host "[local]", user "ambari", database "ambari", SSL off
答案 0 :(得分:1)
使用开关-c command
或-f filename
,即:
$ psql -U ambari -c "SELECT ... ;" ambari # > result.file
或:
$ cat file.sql
SELECT
... ;
$ psql -U ambari -f file.sql ambari # > result.file
可能是-f
,因为您的查询似乎很长。使用> result.file
将查询结果存储到文件中。
关于密码,将以下类型的条目存储到用户主目录中的.pgpass
文件中:
$ cat >> ~/.pgpass
#hostname:port:database:username:password
localhost:5432:ambari:ambari:t00M4NY53CR3t5
并仅将其权限设置为用户的眼睛:
$ chmod 600 ~/.pgpass
此外,如果数据库未在本地主机中运行,则考虑使用psql -h hostname
(这也需要反映在.pgpass
条目中)。
答案 1 :(得分:1)
我正在使用这个
@Bean
然后从文件中运行sql脚本
dbhost=localhost
dbport=5432
dbuser=user
dbpass=pass
dbname=test
export PGPASSWORD="$dbpass"
dbopts="-h $dbhost -p $dbport -U $dbuser -d $dbname"
或者通过查询var
psql $dbopts < "$path_to_sql_script"
pgpass也可以像这样在特殊文件query="
SELECT 1;
...
"
psql $dbopts <<< "$query"
中设置
~/.pgpass