Reputation: 5648
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
Upvotes: 4
Views: 9433
Reputation: 75785
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
Upvotes: 1
Reputation: 169304
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 :-)
Upvotes: 2
Reputation: 91309
You can try to give the column an alias, i.e.:
self.cursor.execute('select LPPLNM, LPPDR# as LPPDR from BSYDTAD.LADWJLFU')
Upvotes: 5
Reputation: 192921
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 ...
Upvotes: 8