Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pypyodbc Can't refer to column names using SQL Server Localdb

Total Python noob here. I am writing a script against a sql server local db and cannot call values based on the column name.

cnxn = pypyodbc.connect('Driver={SQL Server Native Client 11.0};Server=(localdb)\database;integrated security = true')
cursor = cnxn.cursor()
cursor.execute("SELECT username FROM [students].[dbo].[users]")
rows = cursor.fetchall()
for row in rows:
    print (row.username)
cnxn.close()

returns AttributeError: 'Row' object has no attribute 'username'

print (row) 

dumps the data as expected. And modifying the code to:

cursor.execute("SELECT username FROM [students].[dbo].[users]")
rows = cursor.fetchall()
x=0
for row in rows:
    print (row.cursor_description[x][0])
cnxn.close()

returns username for each record.

Why can I not call row.username?

like image 750
edvan22 Avatar asked Mar 14 '23 04:03

edvan22


1 Answers

Use print (row["username"])

pypyodbc does not support column properties as pyodbc does, only a column collection that you can get by index or it's header name.

pyodbc uses row.attribute syntax, pypyodbc uses row["attribute"] syntax.

like image 135
krtek Avatar answered Mar 17 '23 06:03

krtek