将 cursor.callproc 的结果保存在字典中

Save Results from cursor.callproc in dict

我正在尝试使用存储过程从 MySQL 数据库中获取一些数据并将其存储在字典中(如 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': None, 'locations_id': 0, 'groups_id_tech': 0, 'consumableitemtypes_id': 0, 'id': 1, 'comment': '', 'is_deleted': 0, 'ref': ''}]

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

print(result['name'])

TypeError: list indices must be integers, not str

和:

print(result(name))

NameError: name 'name' is not defined

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

看了你贴的词典列表,我觉得你打印的方式有问题。

我觉得这个

print(result['name'])

应该变成这样

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

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