简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM