从 shell 脚本执行 sql 查询

Execute sql queries from shell script

我需要从 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

使用开关-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 条目中)。

我正在使用这个

dbhost=localhost
dbport=5432
dbuser=user
dbpass=pass
dbname=test
export PGPASSWORD="$dbpass"
dbopts="-h $dbhost -p $dbport -U $dbuser -d $dbname"

然后 运行 sql 来自文件的脚本

psql $dbopts < "$path_to_sql_script"

或从查询变量

query="
SELECT 1;
...
"
psql $dbopts <<< "$query"

也可以像这样在特殊文件~/.pgpass中设置pgpass

echo "$dbhost:$dbport:$dbname:$dbname:$dbpass" > ~/.pgpass
chmod 600 ~/.pgpass