[Tutor] best approach to db-api imports and cursor calls
Serdar Tumgoren
zstumgoren at gmail.com
Wed Aug 12 22:36:53 CEST 2009
Hi everyone,
Was wondering if you could advise on best practices when it comes to
reusing a database cursor.
I'm working on a program that must hit a database several times.
Basically, I pull some data, process it, and then use a portion of
that data as parameters for the next call. And then I rinse and
repeat.
So my question: Is it better to start off my program (or main
function) with a global import of the database module and a global
cursor object, and then pass that cursor to each method that requires
it?
>>> import cx_Oracle
>>> db = cx_Oracle.connect()
>>> cur = db.cursor()
>>> x = MyObject()
>>> x.getData(cur)
>>> x.processData()
>>> x.getMoreData(cur)
Or is it better to import, connect and create the cursor inside each
method where it's needed?
On the one hand, I know you're supposed to avoid polluting the global
namespace, but on the other, it seems like I'd be generating a lot of
duplicate code by adding import/connect/cursor to each method.
Or should I use some middle road like creating a global function that
returns a cursor object, and then call that inside each method that
needs it?
Advice, as always, is greatly appreciated.
Regards,
Serdar
More information about the Tutor
mailing list