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
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 ...
You can try to give the column an alias, i.e.:
self.cursor.execute('select LPPLNM, LPPDR# as LPPDR from BSYDTAD.LADWJLFU')
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