Margaret
Margaret

Reputation: 5929

Append all fields returned as attributes of a pyodbc cursor to a user-defined data type

I have code along these lines:

classinstance.col1 = queryresult.col1
classinstance.col2 = queryresult.col2
classinstance.col3 = queryresult.col3
classinstance.col4 = queryresult.col4

Which adds variables to the classinstance and assigns the values of the queryresult column with the same name as the variable.

I am hoping to make my code a little more flexible, and not need to identify the columns by name. To this end, I was wondering if there was some way to do a loop over all the columns, rather than handle each one individually. Something like this (This is psuedocode rather than actual code, since I'm not sure what it should actually look like):

for each var in vars(queryresult):
    classinstance.(var.name) = var.value

Is this possible? What does it require? Is there some fundamental misunderstanding on my part?

Upvotes: 1

Views: 789

Answers (1)

Bryan
Bryan

Reputation: 17693

I'm assuming there's only one row in the result for the following example (built with help from comments here). The key component here is zip(row.cursor_description, row) used to get column names from pyodbc.Row object.

# convert row to an object, assuming row variable contains query result
rowdict = { key[0]:value for (key, value) in zip(row.cursor_description, row) }

# loop through keys (equivalent to column names) and set class instance values
# assumes existing instance of class is variable classinstance
for column in rowdict.keys():
    classinstance[column] = rowdict[column]

Upvotes: 1

Related Questions