[英]Using pipes to redirect a function-generated SQL query to the psql command
I have a script that generates an SQL query as text eg 我有一个脚本,可以将SQL查询生成为文本,例如
...
return "SELECT COUNT(*) FROM important_table"
which I would then like to run on a PostgreSQL database. 然后我要在PostgreSQL数据库上运行。 I can do this in two lines like this:
我可以这样做两行:
python SQLgeneratingScript.py parameters > temp.sql
psql -f temp.sql -d my_database
But seems like I should be able to one-line it with pipes, but I don't know how. 但是似乎我应该能够用管道将其单行,但是我不知道如何。
python SQLgeneratingScript.py parameters|psql -d my_database
i don't know why you are not using a python postgresql connector like psycopg2 ,but well if you want to do what you are trying to do using Unix command redirection you will have to do it like this in your code 我不知道你为什么不使用像psycopg2这样的python postgresql连接器,但是如果你想使用Unix命令重定向做你想做的事情,你将不得不在你的代码中这样做
...
print "SELECT COUNT(*) FROM important_table" # or use sys.stdout.write()
this will write in your file temp.sql
if you have ran your command like this: 如果你运行了这样的命令,这将在你的文件
temp.sql
写入:
python SQLgeneratingScript.py parameters > temp.sql
but well i will suggest writing in you file in python like this 但我会建议你在python中写这样的文件
def generate_sql():
...
return "SELECT COUNT(*) FROM important_table"
with open('temp.sql', 'w') as f
sql = generate_sql()
f.write(sql)
or more use psycopg2
to execute directly your sql 或者更多使用
psycopg2
直接执行你的sql
import psycopg2
def generate_sql():
...
return "SELECT COUNT(*) FROM important_table"
conn = psycopg2.connect("dbname= ...")
cur = conn.cursor()
sql = generate_sql()
cur.execute(sql)
conn.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.