嵌套if if one in循环Python

时间:2017-08-23 19:16:36

标签: python sql nested-if

我正在尝试构建包含边界约束的飞行有效SQL语句。我的问题是有没有简单的方法使用for循环构建有效的SQL语句,如下所示?

sql = 'SELECT * from table '
firststatment = True
r = dict(request.query)
for k,v in r.items():
    if firststatment:
        sql = sql + ' where {} = {}'.format(k,v)
        firststatment = False
    else:
        sql = sql + ' and {} = {}'.format(k,v)

或在这种情况下最好使用像

这样的结构
if bondarydate1 and bondarydate2:
    sql = sql + ' where year(date) between ({} and {})'.format(bondarydate1, bondarydate2)
    marker = True
elif bondarydate1:
    sql = sql + ' where year(date) = {}'.format(bondarydate1)
    marker = True
elif bondarydate2:
    sql = sql + ' where year(date) = {}'.format(bondarydate2)
    marker =True

if marker and boundaryparam2:
    sql = sql + ' and boundaryparam2 = {}'.format(boundaryparam2)
elif boundaryparam2:
    sql = sql + ' where boundaryparam2 = {}'.format(boundaryparam2)
    marker = True

if marker and boundaryparam3:
    sql = sql+' and boundaryparam3 = {}'.format(boundaryparam3)
elif boundaryparam3:
    sql = sql + ' where boundaryparam3 = {}'.format(boundaryparam3)
    marker = True

if marker and boundaryparam4:
    sql = sql + ' and boundaryparam4 = {}'.format(boundaryparam4)
elif boundaryparam4:
    sql = sql + ' where boundaryparam4 = {}'.format(boundaryparam4)
    marker = True

if marker and boundaryparam5:
    sql = sql + ' and boundaryparam5 = {}'.format(boundaryparam5)
elif boundaryparam5:
    sql = sql +' where boundaryparam5 = {}'.format(boundaryparam5)

基本上我正在尝试以某种方式丰富有效的SQL语句,如下所示

SELECT * from x where date between bondarydate1 and boundarydate2  and column1 = dhkjf and column2 = 343

P.S: 是否有一些简短的方法来构建SQL,它只包含r['predefined']r = {'predefined':'someValue', 'sapmKey':'spamvalue'}等硬编码密钥的边界,以便在查询中不插入垃圾邮件值?

1 个答案:

答案 0 :(得分:2)

,但建立这样的查询并不是一个好主意:它可以轻松地允许 SQL注入

您可以使用以下代码执行此操作:

constraints = ' AND '.join('{} = {}'.format(*t) for t in r.items())
sql = 'SELECT * FROM table WHERE {}'.format(constraints)

但这不安全:如果密钥或值包含例如反引号,黑客可能会以导出您的数据库为目的。

我建议至少转义值(通常 - 希望 - 用户只能控制值),然后你可以使用像%s这样的占位符,让像MySQLdb这样的库逃避这些值。例如:

constraints = ' AND '.join('{} = %s'.format(k) for k in r.keys())
sql = 'SELECT * FROM table WHERE {}'.format(constraints)
cursor.execute(sql, r.values())

此外,存在许多Python库(如SQLAlchemy),其中可以安全地构建SQL查询(当然,鉴于库本身是安全的)。这通常会对您的应用程序的安全性产生积极影响。

因此,我强烈建议您使用某种库与数据库通信。通常它会提供额外的抽象级别,这很好,而且它通常可以保护您免受大多数安全漏洞的侵害。