简体   繁体   中英

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)

@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:

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. Also please return something on your pages or the user will just get stuck when the page is accessed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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