gpt4 book ai didi

Python - 从Sql Server语句中的字段获取值

转载 作者:太空宇宙 更新时间:2023-11-03 16:51:42 24 4
gpt4 key购买 nike

我在 SQLSERVER 数据库中有一个动物表,其中包含两个字段:id 和 name。

我正在尝试这样做:

cnxn = pyodbc.connect(
'Trusted_Connection=yes;DRIVER={SQL Server};SERVER=localhost; DATABASE=TEST;UID=sa;PWD=123456'
)

id = 1

cursor = cnxn.cursor()

cursor.execute('SELECT id, name FROM animal WHERE id=?', (id,))

for row in cursor.fetchall():
print row.name

但由于某种原因,它给了我下一个错误:

Traceback (most recent call last):

AttributeError: 'Row' object has no attribute 'name'

任何人都可以帮助我从字段中获取值并将其保存在变量中吗?

最佳答案

使用print row[1]代替print row.namefetchall() 返回一个元组列表,格式为 [(1234, 'Alice Cooper'), ...]

关于Python - 从Sql Server语句中的字段获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35800501/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com