0

Here, in the update part a new duplicate is getting created instead of updating the existing record. Please help!

def addBooks(title, quantity):
    c.execute('SELECT * FROM books')
    for i, j in c.fetchall():
        if i == title:
            c.execute('UPDATE books SET quantity = ? WHERE title = ?', (j+quantity, title))
            conn.commit()
        else:
            c.execute('INSERT INTO books VALUES (?, ?)', (title, quantity))
            conn.commit()

1 Answers1

0

I think you just want an update here:

def addBooks(title, quantity):
    c.execute('UPDATE books SET quantity = quantity + ? WHERE title = ?', (quantity, title,))
    conn.commit()

Your current code has multiple problems. First of all, doing SELECT * in your first (unnecessary) select is semantically incorrect, because you should be explicitly listing out which columns you want. Also, there is no need to iterate the result set from this select to update each record. UPDATE is already a set-based operation which will target every record in the table. There is also no need to be doing an INSERT here if I understand your requirement.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360