0

我正在尝试MySQL使用存储过程从数据库中获取一些数据并将其存储在 dict 中(如 blair here所述):

    def createProduct(self):
    self.cursor.callproc('newProduct')

    result = []
    for recordset in self.cursor.stored_results():
        for row in recordset:
            result.append(dict(zip(recordset.column_names,row)))
            print(result)

光标是使用选项创建的dictionary=True。的输出print(result)是:

[{'manufacturers_id':0,'alarm_threshold':10,'users_id_tech':0,'name':'item1','entities_id':0,'notepad':无,'locations_id':0,'groups_id_tech': 0,'consumableitemtypes_id':0,'id':1,'comment':'','is_deleted':0,'ref':''}]

我尝试使用以下代码访问键的值name(即item1):

print(result['name'])

TypeError:列表索引必须是整数,而不是 str

和:

print(result(name))

NameError:名称“名称”未定义

我认为来自 blair 的代码会创建一个可以通过键访问其值的字典(例如“名称”)?这是错的还是我做错了什么?

4

1 回答 1

1

查看您发布的字典列表,我认为您的打印方式存在问题。

我认为这

print(result['name'])

应该变成这个

print(result[0]['name'])

因为您正在尝试访问列表中的字典。希望它有效。

于 2015-04-13T12:04:36.927 回答