[Answered ]-Python Cursor SELECT columns dynamically

0👍

Finally I built a string with all the elements in the list, and I passed this string to the query string:

columnList = ['Field1', 'Field2']

for idx, field in enumerate(columnList):
    if idx != len(columnList)-1:
        listFields += field + ', '
    else:
        listFields += field

cursor.execute("SELECT %s FROM table", listFields)

This is not what I was looking for, and… I am not proud of it…, but even like this is faster than iterate a django queryset

2👍

Only one list is expected as second argument in the current form of execute but you are passing a list within a list. Try this:

columnList = ['Field1', 'Field2']
cursor.execute("SELECT %s, %s FROM table", columnList)
👤arocks

Leave a comment