Can I pass a cursor to a function?

Steve Holden sholden at holdenweb.com
Thu Jun 28 15:28:39 EDT 2001


<jestes39 at yahoo.com> wrote ...
> I am trying to figure out whether or not Python will let me pass a
> cursor variable to a function so that I don't have to create another
> connection instance to Oracle. Here's the chunk of code:
>
You're looking at a non-existent problem ... see below.

>     try:
>         dbc = odbc.odbc(conn_str)
>         crsr = dbc.cursor()
>     except:
>         raise database_error
>
>     while 1:
>         sql = "SELECT DATA, ROWID FROM <TABLE_NAME>;"
>         crsr.execute(sql)
>         records = crsr.fetchall()
>         for record in records:
>             pid = `record`[2:4]
>             rowid = `record`[129:-2]
>             row_flag = 'TRUE'
>
>             if row_flag == 'TRUE':
>                 if pid == 'RE':
>                     receipt_flag = 'TRUE'
>                     receipt_mod.receipt(crsr,record)
>             else:
>                 time.sleep(5)
>
> I set data up so that both if statements evaluate to true, the flag
> is set, and the receipt function is invoked. I get this error if I
> try to pass dbc or crsr:
>
>   Traceback (most recent call last):
>   File "C:\proc_mgr.py", line 33, in ?
>   receipt_mod.receipt(crsr,record)
>   AttributeError: receipt
>
The problem here seems to be with your receipt_mod. Python is telling you
that (module? class? whatever...) does not have a "receipt" attribute - in
other words, you are referring to a non-existent name. I'd be *very*
surprised if this worked with only the second argument.

> If I just pass the record variable, things work fine. Is there a way
> that I can pass crsr that I am not seeing or can I make it global and
> use it in the function that way? Any help or suggestions will be
> appreciated. Thanks.
>
You can pass cursors just like anything else as an argument. For example,
here's a "cursor prettyprinter" function I wrote to give me a legible output
from random database queries.

def cpp(cursor, t = None):
    """Return the result of the last operation on a cursor,
    retrieving unless it is provided as an argument."""
    print
    d = cursor.description
    if not d:
        return "\n#### NO RESULTS ###\n"
    if not t:
        try:
            t = cursor.fetchall()
        except: # XXX should specify exception type
            return """\n###EXCEPTION ON FETCHING RESULTS###\nException
data:\n%s\n(%s)"""\
                    % (sys.exc_type, sys.exc_value)
    names = []
    lengths = []
    rules = []
    col = 0
    for dd in d:
        l = dd[1]
        if not l:
            l = 12
        l = max([l, len(dd[0])] + [len(str(t[i][col])) for i in
range(len(t))])
        names.append(str(dd[0]))
        lengths.append("%%%ss" % l)
        rules.append("-"*l)
        col += 1
    format = " ".join(lengths)+"\n"
    result = "\n" + format % tuple(names)
    result += format % tuple(rules)
    for row in t:
        result += format % row
    return result

regards
 Steve
--

http://www.holdenweb.com/






More information about the Python-list mailing list