简体   繁体   中英

python sqlite3 conditional query

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)

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.

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