简体   繁体   English

有没有办法从Python(使用cx_Oracle)运行保存的SQL查询?

[英]Is there a way to run a saved SQL query from Python (using cx_Oracle)?

I have been using cx_Oracle to perform SQL queries on an Oracle database in Python. 我一直在使用cx_Oracle在Python中的Oracle数据库上执行SQL查询。 So far I have been pasting these queries into strings and then running them using the cursor.execute() function that comes with cx_Oracle: 到目前为止,我一直将这些查询粘贴到字符串中,然后使用cx_Oracle附带的cursor.execute()函数运行它们:

#simple example
query = """SELECT *
           FROM my_table"""
cursor.execute(query)

However, my select queries have gotten quite complex, and the code is starting to look a bit messy. 但是,我的选择查询已经变得非常复杂,并且代码开始看起来有些混乱。 I was wondering if there were any way to simply save the SQL code into a .sql file and for Python or cx_Oracle to call that file? 我想知道是否有任何方法可以将SQL代码简单地保存到.sql文件中,并让Python或cx_Oracle调用该文件? I thought something like that might be simple to find using Google, but my searches are oddly coming up dry. 我以为使用Google可以很容易找到这样的东西,但是奇怪的是我的搜索变得干dry了。

Well, you can certainly save SQL code to a file and load it: 好吧,您当然可以将SQL代码保存到文件中并加载它:

query = open('foo.sql', 'r').read()
cursor.execute(query)

I can't find any reference to saved queries in cx_Oracle, so that may be your best bet. 我在cx_Oracle中找不到对已保存查询的任何引用,因此这可能是您最好的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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