pypyodbc无法使用SQL Server Localdb引用列名

5

我完全不懂Python,正在编写一个与SQL Server本地数据库相对应的脚本,但无法通过列名称调用值。

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()

返回 AttributeError: 'Row' 对象没有属性 'username'

print (row) 

转储数据正如预期的那样。将代码修改为:
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()

返回每条记录的用户名。

为什么我不能调用row.username?

1个回答

8

使用 print (row["username"])

pypyodbc 不支持像 pyodbc 一样的列属性,只支持通过索引或标题名称获取列集合。

pyodbc 使用 row.attribute 语法,而 pypyodbc 使用 row["attribute"] 语法。


5
pypyodbc使用小写字母来表示属性名称。 - Henrik

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接