繁体   English   中英

使用管道将函数生成的SQL查询重定向到psql命令

[英]Using pipes to redirect a function-generated SQL query to the psql command

我有一个脚本,可以将SQL查询生成为文本,例如

...
return "SELECT COUNT(*) FROM important_table" 

然后我要在PostgreSQL数据库上运行。 我可以这样做两行:

python SQLgeneratingScript.py parameters > temp.sql 
psql -f temp.sql -d my_database 

但是似乎我应该能够用管道将其单行,但是我不知道如何。

python SQLgeneratingScript.py parameters|psql -d my_database

我不知道你为什么不使用像psycopg2这样的python postgresql连接器,但是如果你想使用Unix命令重定向做你想做的事情,你将不得不在你的代码中这样做

...
print "SELECT COUNT(*) FROM important_table"  # or use sys.stdout.write()

如果你运行了这样的命令,这将在你的文件temp.sql写入:

python SQLgeneratingScript.py parameters > temp.sql

但我会建议你在python中写这样的文件

def generate_sql():
   ...
   return "SELECT COUNT(*) FROM important_table"

with open('temp.sql', 'w') as f
   sql = generate_sql()
   f.write(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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM