TypeError('list indices must be integers, not str',)

TypeError('list indices must be integers, not str',)

我写了这段代码,我试图在 table(数据库 sqlite)

中添加一个新行
@get('/inventory/add')
def inventory_add(db):
    db.execute("INSERT INTO inventory (name, category, location, date, amount) VALUES (?, ?, ?, ?, ?)", (item['name'], item['category'], item['location'], item['date'],  item['amount']))

    db.commit()

起初我执行它时得到:

NameError("global name 'item' is not defined",)

所以我在互联网上四处搜索,在我对 python 缺乏经验的情况下,我决定将项目声明为列表,希望它能起作用:

item=[]
@get('/inventory/add')
def inventory_add(db):
    db.execute("INSERT INTO inventory (name, category, location, date, amount) VALUES (?, ?, ?, ?, ?)", (item['name'], item['category'],    item['location'], item['date'],  item['amount']))

    db.commit()

所以在 运行 上面的代码之后我得到了这个:

TypeError('list indices must be integers, not str',)

这里你需要的是字典,而不是列表。所以,试试这个:

item={'name':'somename', 'category':'somecat','location':'someloc', 'date':'somedate','amount':'someamt'}

(不要在这里声明空字典,如果程序不知道去哪里查找字典显然会抛出错误) 然后试试你的代码,它应该可以工作。

对于 Cursor 错误,如 DYZ 所说,您正在尝试提交游标,但您应该尝试提交与数据库建立连接的实例。另外请 return 在您的页面上添加一些内容,否则用户在访问该页面时会卡住。