In cx_Oracle (or Oracle in general), is it possible to allocate a cursor for each query, or to reuse a cursor across several queries.
def getSomeData(curs): # case 1: pass in a cursor, which is generally
curs.execute('select ...') # reused across queries
return curs.fetchall()
def getSomeData(conn): # case 2: pass in a connection,allocate
curs=conn.cursor() # a cursor for this query
curs.execute('select ...')
return curs.fetchall()
Of course, both approaches return the same data.
What are the tradeoffs between the two approaches? Is one particularly more or less efficient? Are there any potential pitfalls to reusing a cursor over many queries?
To execute a multi-row query, Oracle opens an unnamed work area that stores processing information. A cursor lets you name the work area, access the information, and process the rows individually.
there is no limit (i'm aware of) to the number of rows a cursor can process. Obviously, if you try and process 50 million records from a cursor, your program won't likely finish anytime soon.
You can't use a function returning a ref cursor in that way. It would usually be used in the context of passing a result set pointer around in PL/SQL. You can get close but you will need to use a pipelined function and without knowing exactly what you want an answer including that would be pointless.
You can re-use a cx_Oracle cursor as much as you like, no problem. If you're executing thousands of small queries in a small space of time, you might see a slight performance improvement by re-using the cursor, but I doubt it.
I will sometimes create new cursors, and other times re-use an existing one, depending on whether it makes the code easier to read and understand.
For example, if I have a variety of procedures that need to access the database, I might pass an Oracle connection object around, or a cursor created on that connection.
Whatever makes your code more readable and easier to maintain is what I'd go for.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With