简体   繁体   English

转义动态sqlite查询?

[英]Escaping dynamic sqlite query?

I'm currently building SQL queries depending on input from the user.我目前正在根据用户的输入构建 SQL 查询。 An example how this is done can be seen here:可以在此处查看如何完成此操作的示例:

def generate_conditions(table_name,nameValues):
    sql = u""
    for field in nameValues:
        sql += u" AND {0}.{1}='{2}'".format(table_name,field,nameValues[field])
    return sql

search_query = u"SELECT * FROM Enheter e LEFT OUTER JOIN Handelser h ON e.Id == h.Enhet WHERE 1=1"

if "Enhet" in args:
    search_query += generate_conditions("e",args["Enhet"])
c.execute(search_query)

Since the SQL changes every time I cannot insert the values in the execute call which means that I should escape the strings manually.由于每次我无法在执行调用中插入值时 SQL 都会更改,这意味着我应该手动转义字符串。 However, when I search everyone points to execute...但是,当我搜索每个人都指向执行...

I'm also not that satisfied with how I generate the query, so if someone has any idea for another way that would be great also!我对生成查询的方式也不太满意,所以如果有人对另一种方式有任何想法,那也很棒!

You have two options:您有两个选择:

  1. Switch to using SQLAlchemy ;切换到使用SQLAlchemy it'll make generating dynamic SQL a lot more pythonic and ensures proper quoting.它将使生成动态 SQL 更加 Pythonic确保正确引用。

  2. Since you cannot use parameters for table and column names, you'll still have to use string formatting to include these in the query.由于您不能对表名和列名使用参数,因此您仍然必须使用字符串格式将这些包含在查询中。 Your values on the other hand, should always be using SQL parameters, if only so the database can prepare the statement.另一方面,您的应该始终使用 SQL 参数,前提是数据库可以准备语句。

    It's not advisable to just interpolate table and column names taken straight from user input, it's far too easy to inject arbitrary SQL statements that way.这是不可取的,直接从用户的输入采取公正插值表和列名,这是容易注入任意SQL语句的方式。 Verify the table and column names against a list of such names you accept instead.对照您接受的此类名称列表验证表和列名称。

    So, to build on your example, I'd go in this direction:因此,以您的示例为基础,我将朝这个方向发展:

     tables = { 'e': ('unit1', 'unit2', ...), # tablename: tuple of column names } def generate_conditions(table_name, nameValues): if table_name not in tables: raise ValueError('No such table %r' % table_name) sql = u"" params = [] for field in nameValues: if field not in tables[table_name]: raise ValueError('No such column %r' % field) sql += u" AND {0}.{1}=?".format(table_name, field) params.append(nameValues[field]) return sql, params search_query = u"SELECT * FROM Enheter e LEFT OUTER JOIN Handelser h ON e.Id == h.Enhet WHERE 1=1" search_params = [] if "Enhet" in args: sql, params = generate_conditions("e",args["Enhet"]) search_query += sql search_params.extend(params) c.execute(search_query, search_params)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM