views:

290

answers:

4

I'm using pyodbc to query an AS400 (unfortunately), and some column names have hashes in them! Here is a small example:

self.cursor.execute('select LPPLNM, LPPDR# from BSYDTAD.LADWJLFU')

for row in self.cursor:
 p = Patient()
 p.last = row.LPPLNM
        p.pcp = row.LPPDR#

I get errors like this obviously:

 AttributeError: 'pyodbc.Row' object has no attribute 'LPPDR'

Is there some way to escape this? Seems doubtful that a hash is even allowed in a var name. I just picked up python today, so forgive me if the answer is common knowledge.

Thanks, Pete

+7  A: 

Use the getattr function

p.pcp = getattr(row, "LPPDR#")

This is, in general, the way that you deal with attributes which aren't legal Python identifiers. For example, you can say

setattr(p, "&)(@#$@!!~%&", "Hello World!")
print getattr(p, "&)(@#$@!!~%&")  # prints "Hello World!"

Also, as JG suggests, you can give your columns an alias, such as by saying

SELECT LPPDR# AS LPPDR ...
Eli Courtwright
Works great, thanks a lot!
slypete
+5  A: 

You can try to give the column an alias, i.e.:

 self.cursor.execute('select LPPLNM, LPPDR# as LPPDR from BSYDTAD.LADWJLFU')
JG
+2  A: 

self.cursor.execute returns a tuple, so this would also work:

for row in self.cursor:
        p = Patient()
        p.last = row[0]
        p.pcp = row[1]

But I prefer the other answers :-)

Adam Bernier
+1  A: 

The question has been answered, but this is just another alternative (based on Adam Bernier's answer + tuple unpacking) which I think is the cleanest:

for row in self.cursor:
    p = Patient()
    p.last, p.pcp = row
dF