我不确定我的问题是django,sqlite3,与regexp语法的一些奇怪的交互,还是只是我:我有一个BAD版本的SQL查询要由django.model正确处理:
qryStrBAD = "SELECT idx, cdate, beat FROM app_database where cc regexp '^%s'" % (cc)
for c in MyModel.objects.raw(qryStrBAD):
这是有效的。但当然我不想允许注射攻击,所以我把它换成raw()
推荐的params列表版本:
qryStr = "SELECT idx, cdate, beat FROM app_database where cc regexp '^%s'"
for c in MyModel.objects.raw(qryStr,[cc]):
但使用此抛出
DatabaseError at <URL>
Incorrect number of bindings supplied. The current statement uses 0, and there are 1 supplied
甚至更奇怪的是,通过追溯日志戳戳似乎表明该替换正在正确完成:
** .../app/views.py in plotResults
for c in MyModel.objects.raw(qryStr,[cc]):
...
Local vars
qryStr: "SELECT idx, cdate, beat FROM app_database where cc regexp '^%s'"
cc: u'LARCENY_THEFT'
** /Library/Python/2.7/site-packages/django/db/models/query.py in __iter__
<RawQuerySet: u"SELECT idx, cdate, beat FROM app_database where cc regexp '^LARCENY_THEFT'">
** /Library/Python/2.7/site-packages/django/db/models/sql/query.py in _execute_query
<RawQuery: u"SELECT idx, cdate, beat FROM app_database where cc regexp '^LARCENY_THEFT'">
** /Library/Python/2.7/site-packages/django/db/backends/util.py in execute
Local vars
params: [u'LARCENY_THEFT']
sql: u"SELECT idx, cdate, beat FROM app_database where cc regexp '^LARCENY_THEFT'"
** /Library/Python/2.7/site-packages/django/db/backends/sqlite3/base.py in execute
six.reraise(utils.DatabaseError, utils.DatabaseError(*tuple(e.args)), sys.exc_info()[2])
...
ProgrammingError('Incorrect number of bindings supplied. The current statement uses 0, and there are 1 supplied.',)
Local vars
params: [u'LARCENY_THEFT']
query: u"SELECT idx, cdate, beat FROM app_database where cc regexp '^?'"
** /Library/Python/2.7/site-packages/django/db/backends/sqlite3/base.py in execute
Local vars
params: [u'LARCENY_THEFT']
query: u"SELECT idx, cdate, beat FROM app_database where cc regexp '^?'"
任何猜测是什么?
答案 0 :(得分:0)
不要尝试将^
与查询字符串中的参数组合在一起。
相反,请单独创建正则表达式,然后将其用作参数。
startswith_cc = '^%s' % startswith_cc
qryStr = "SELECT idx, cdate, beat FROM app_database where cc regexp %s"
for c in MyModel.objects.raw(qryStr, [startswith_cc]):
...