Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the tradeoffs of reusing a cursor vs. creating a new cursor?

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?

like image 781
Mark Harrison Avatar asked Jan 09 '10 22:01

Mark Harrison


People also ask

Why do we use cursor in Oracle?

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.

How many rows a cursor can hold in Oracle?

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.

Can we use cursor in function Oracle?

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.


1 Answers

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.

like image 51
Jeffrey Kemp Avatar answered Oct 22 '22 20:10

Jeffrey Kemp