I have written several functions to get particular items of data like this:
def get_short_desc(self, part_num):
sql = 'SELECT impShortDescription FROM Parts '
sql += 'WHERE impPartID LIKE ?'
self.cursor.execute(sql, [part_num])
item = self.cursor.fetchone().impShortDescription
return item
I want to paramaterise the functions so I am not repeating myself (DRY):
def get_part_entry_item(self, var, part_num):
sql = 'SELECT ? FROM Parts '
sql += 'WHERE impPartID LIKE ?'
self.cursor.execute(sql, [var, part_num])
item = getattr(self.cursor.fetchone(), var)
return item
The execute statement passes the value of part_num (a string) with single quotes which is correct. When the column name variable var = 'impShortDescription' the resulting SQL is effectively SELECT 'impShortDescription'... so the item returned is
('impShortDescription', )
so getattr(self.cursor.fetchone(), var) causes the error
AttributeError: 'pyodbc.Row' object has no attribute 'impShortDescription'
How do I pass a column name without the quotes?