SQLite insert if not exist else increase integer value SQLite insert if not exist else increase integer value sqlite sqlite

SQLite insert if not exist else increase integer value


If you want to have only one column for each date, then you should declare it as UNIQUE, or even as the PRIMARY KEY for the table.

If you do that, then you can declare the Quantity column as INTEGER NOT NULL DEFAULT 0. Your table would then be defined as:

CREATE TABLE IF NOT EXISTS table (    Date TEXT PRIMARY KEY,    Quantity INTEGER NOT NULL DEFAULT 0);

Then when you want to add to a specific date, you run:

# assuming 'db' is your sqlite3 databasedate_to_insert = '12/5/2013'amount_to_add = 20db.execute('INSERT OR IGNORE INTO table(Date) VALUES(?)', (date_to_insert,))db.execute('UPDATE table SET Quantity = Quantity + ? WHERE Date = ?', (amount_to_add, date_to_insert))