简体   繁体   English

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

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

I wrote this piece of code where I am trying to add a new row to a table (database sqlite) 我写了这段代码,试图在表中添加新行(数据库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()

At first when I executed it I got: 刚开始执行时,我得到:

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

so I digged around internet an in my inexperience with python I decided to declare item as a list in hope it would work: 所以我在对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()

So after running the above code I got this: 因此,在运行上面的代码后,我得到了:

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

What you need here is a dictionary, not a list. 您需要的是字典,而不是列表。 So, try this: 因此,请尝试以下操作:

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

(don't declare empty dictionary here, if the program doesn't know where to look in the dictionary it will obviously throw an error) Then try your code, it should be working. (不要在此处声明空字典,如果程序不知道在字典中查找的位置,显然会引发错误)。然后尝试编写代码,它应该可以工作。

For the Cursor error, like DYZ said, you are trying to commit the cursor, but you should try to commit the instance with which you have made the connection to the database. 对于Cursor错误,就像DYZ所说的那样,您正在尝试提交游标,但是您应该尝试提交与数据库建立连接的实例。 Also please return something on your pages or the user will just get stuck when the page is accessed. 另外,请在页面上返回一些内容,否则访问该页面时用户将被卡住。

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

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