[英]python sqlite3 conditional query
Sqlite3 table Sqlite3 表
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 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当我使用
update(1, 3, 4, 5)
它工作,但在 update(1, 3, 4) 它给了我Error: NOT NULL constraint failed: t.p3
什么是正常的,因为我应该做
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.就个人而言,出于安全原因,我会使用 ORM 而不是原始 SQL。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.