繁体   English   中英

TypeError('列表索引必须是整数,而不是str',)

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

我写了这段代码,试图在表中添加新行(数据库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声明为列表,希望它能起作用:

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所说的那样,您正在尝试提交游标,但是您应该尝试提交与数据库建立连接的实例。 另外,请在页面上返回一些内容,否则访问该页面时用户将被卡住。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM