0

Sqlite3 table

CREATE TABLE t (
    id INTEGER PRIMARY KEY,
    p1 INTEGER NOT NULL,
    p2 INTEGER NOT NULL,
    p3 INTEGER NOT NULL
)
INSERT INTO t (1, 11, 12, 13)

Python

def update(id, p1=None, p2=None, p3=None):
    db = self.get_db()
    db.execute('UPDATE t SET p1=?, p2=?, p3=? WHERE id=?', (p1, p2, p3, id))

When I use update(1, 3, 4, 5) it works, but on update(1, 3, 4) it gives me Error: NOT NULL constraint failed: t.p3 what is normal because i should do

if not p3:
    db.execute('UPDATE t SET p1=?, p2=? WHERE id=?', (p1, p2, id))

Is it possible to get it done quite simple ?

for example:

stm = db.prep('UPDATE t SET')
if p1:
    stm.append('p1=?', p1)
if p2:
    stm.append('p2=?', p2)
if p3:
    stm.append('p3=?', p3)
stm.append('WHERE id=?', id)
1
  • "Error: NOT NULL constraint failed: t.p3": You only pass tree parameter, update(1, 3, 4), the fourth will be None which is p3 Commented Feb 12, 2020 at 14:44

1 Answer 1

1

This would be the easiest method I can think of:

def update(self, object_id, p1=None, p2=None, p3=None):  # don't use id as a variable name
    db = self.get_db()
    # if any of the parameters are None, set the new value to what it was already
    db.execute('UPDATE t SET p1=ifnull(?, p1), p2=ifnull(?, p2), p3=ifnull(?, p3) WHERE id=?', (p1, p2, p3, object_id))

Personally, I would use an ORM instead of raw SQL for security reasons.

Sign up to request clarification or add additional context in comments.

2 Comments

Exactly what i was looking for!
What if there is default value like p1 INTEGER NOT NULL DEFAULT=55. How can I use something like. UPDATE t SET p1=ifnull(?, DEFAULT) ... or maybe UPDATE t SET ifnotnull(?, p1=?). I know that there is no default nor second example, but maybe there is some other magical way :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.