我是 python 新手,我想做一个类似的查询:
_c.execute('select * from cases where bi = ? and age = ? and
shape = ? and margin = ? and density = ?',(obj['bi'],
obj['age'], obj['margin'], obj['density']))
当部分参数为
None
时,例如 obj['bi'] = None
,查询搜索 bi = 'None'
时的行.但我希望它在以下情况下搜索该行:'bi is NULL'
一种可能的解决方案是在一系列 if-else 中逐一验证参数的值。例如:
query = 'select * from cases where'
if obj['bi'] is None:
query += ' bi is null'
else:
query += ' bi = ' + str(obj['bi']) + ' and '
...
# do the same if-else for the other parameters
...
_c.execute(query)
但是,在我看来,这并不是最好的解决方案。
问题是,给定问题的最佳解决方案是什么以及如何避免 SQL 注入(inject)。
最佳答案
好的,在启动了一个 python REPL 并玩了一下之后,它比我想象的要简单。 Python sqlite 绑定(bind)将 Python None
进入 SQL NULL
,而不是字符串 'None'
就像你的问题听起来一样。在 SQL 中,=
不匹配 NULL
值,但 IS
将要。所以...
给定一张表foo
看起来像:
a | b
--------------
NULL | 1
Dog | 2
正在做:
c = conn.cursor()
c.execute('SELECT * FROM foo WHERE a IS ?', (None,))
print(c.fetchone())
将返回
(NULL, 1)
行,和c.execute('SELECT * FROM foo WHERE a IS ?', ('Dog',))
print(c.fetchone())
将返回
('Dog', 2)
排。换句话说,使用
IS
不是 =
在您的查询中。
关于python - 使用python在sqlite select查询中动态搜索null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53437461/