2

I have been using cx_Oracle to perform SQL queries on an Oracle database in Python. So far I have been pasting these queries into strings and then running them using the cursor.execute() function that comes with cx_Oracle:

#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? I thought something like that might be simple to find using Google, but my searches are oddly coming up dry.

1
  • .sql files are just text files, and SQL queries in Python are just strings, so there is nothing stopping you from reading queries from a separate file in Python. Commented Oct 24, 2013 at 16:00

1 Answer 1

3

Well, you can certainly save SQL code to a file and load it:

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This is indeed all I was looking for. I presumed there was some simple solution I was overlooking. For reference, I am using the following code: with open(file_name.sql) as f: query = f.read() cursor.execute(query) since the with will properly handle exceptions and also close the file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.