使用 python 在 sqlite select 查询中动态搜索 null
Dynamically search for null in sqlite select query using python
我是 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-els中逐一验证参数的值。例如:
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 注入。
好吧,在启动 python REPL 并尝试了一下之后,它比我想象的要简单。 Python sqlite 绑定将 Python None
变成 SQL NULL
,而不是像你的问题听起来那样变成字符串 'None'
。在 SQL 中,=
不匹配 NULL
值,但 IS
匹配。所以...
给定一个 table foo
看起来像:
a | b
--------------
NULL | 1
Dog | 2
正在做:
c = conn.cursor()
c.execute('SELECT * FROM foo WHERE a IS ?', (None,))
print(c.fetchone())
将 return (NULL, 1)
行,并且
c.execute('SELECT * FROM foo WHERE a IS ?', ('Dog',))
print(c.fetchone())
将 return ('Dog', 2)
行。
换句话说,在查询中使用 IS
而不是 =
。
我是 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-els中逐一验证参数的值。例如:
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 注入。
好吧,在启动 python REPL 并尝试了一下之后,它比我想象的要简单。 Python sqlite 绑定将 Python None
变成 SQL NULL
,而不是像你的问题听起来那样变成字符串 'None'
。在 SQL 中,=
不匹配 NULL
值,但 IS
匹配。所以...
给定一个 table foo
看起来像:
a | b
--------------
NULL | 1
Dog | 2
正在做:
c = conn.cursor()
c.execute('SELECT * FROM foo WHERE a IS ?', (None,))
print(c.fetchone())
将 return (NULL, 1)
行,并且
c.execute('SELECT * FROM foo WHERE a IS ?', ('Dog',))
print(c.fetchone())
将 return ('Dog', 2)
行。
换句话说,在查询中使用 IS
而不是 =
。