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

发布于 2024-10-01 13:42:14 字数 312 浏览 1 评论 0原文

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

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

然后我想在 PostgreSQL 数据库上运行它。我可以用这样的两行来完成此操作:

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

但似乎我应该能够用管道将其排成一行,但我不知道如何操作。

I have a script that generates an SQL query as text e.g.

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

which I would then like to run on a PostgreSQL database. 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

紅太極 2024-10-08 13:42:15
python SQLgeneratingScript.py parameters|psql -d my_database
python SQLgeneratingScript.py parameters|psql -d my_database
人疚 2024-10-08 13:42:15

我不知道你为什么不使用像 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()

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

...
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:

python SQLgeneratingScript.py parameters > temp.sql

but well i will suggest writing in you file in python like this

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

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()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文