0

The following works as expected, however, I'm stuck on referencing the specific column names. For example, print just [OD-Nr] or [OD-Title]

I know if I used an alias, it would be as simple as print(row.id), but I'd rather avoid aliases if possible.

import pyodbc

conn = pyodbc.connect('Driver={SQL Server};'
                      'Server=xxxx;'
                      'Database=xxxx;'
                      'UID=xxxx;'
                      'PWD=xxxx;')

cursor = conn.cursor()
cursor.execute("Select [OD-Nr],[OD-Title] from [dbo].[OD]")

for row in cursor:
    print(row)

Any direction would be appreciated.

John Cappelletti
  • 79,615
  • 7
  • 44
  • 66
  • Did you try enclosing the column names with single quotes or backticks perhaps? – accdias Jan 04 '20 at 03:59
  • use cursor.description to get the column names and then proceed from there, e.g.: https://stackoverflow.com/questions/16519385/output-pyodbc-cursor-results-as-python-dictionary – gregory Jan 04 '20 at 07:19

1 Answers1

0

Taking gregory's suggestion, I looked at cursor.description and added a little twist to convert the array of column names to lowercase.

It would be nice to know any alternative methods.

import pyodbc

conn = pyodbc.connect('Driver={SQL Server};'
                      'Server=xxxx;'
                      'Database=xxxx;'
                      'UID=xxxx;'
                      'PWD=xxxx;')

cursor = conn.cursor()
cursor.execute("Select [OD-Nr],[OD-Title] from [dbo].[OD]")

aCol=[column[0].lower() for column in cursor.description]
iCol=aCol.index('od-title'.lower() )

for row in cursor:
    print(row[iCol])
John Cappelletti
  • 79,615
  • 7
  • 44
  • 66