如何从Shell脚本执行sql查询 [英] how to execute sql queries from a shell script

查看:615
本文介绍了如何从Shell脚本执行sql查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个shell脚本以在postgres中运行一堆查询。

I am writing a shell script to run bunch of queries in postgres.

这是我编写的脚本。

#!/bin/sh
host="172.16.7.102"
username="priyank"
dbname="truaxis"
x=1
echo "Connection done"
while [ $x -le 3 ]
do
        x=$(($x + 1 ))
        echo "Connection $x"
        psql -h $host $dbname $username << EOF
        select * from students where sid = $x;
        EOF
done

此脚本有两个问题。


  1. pgtest1.sh:17:语法错误:文件结尾意外(期望完成)

  1. pgtest1.sh: 17: Syntax error: end of file unexpected (expecting "done")

如何动态在SQL中传递$ x

how do I pass $x in the sql dynamically

我要创建每次迭代都有新的数据库连接。

I want to create new db connection per iteration.

我对Postgre和Shell都是陌生的。

I am new to both postgre and shell.

谢谢

Priyank

推荐答案


1)pgtest1.sh:17:语法错误:文件结尾意外(期望完成)

1) pgtest1.sh: 17: Syntax error: end of file unexpected (expecting "done")

您需要单独在其自己的行中使用EOF(无空格等)

You need to have EOF in its own line alone (without space etc)

     psql -h $host $dbname $username << EOF
        select * from students where sid = $x;
EOF




2)如何传递$ x sql动态

2) how do I pass $x in the sql dynamically



$ sh scriptname.sh value_of_x

然后在您的脚本中

x=$1

这篇关于如何从Shell脚本执行sql查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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