【问题标题】:[Python3][Sqlite3] SQL Injection preventing method that accepts an undefined number of arguments [duplicate][Python3][Sqlite3] SQL Injection preventing method that accepts an undefined number of arguments [duplicate]
【发布时间】:2018-07-30 19:22:35
【问题描述】:

我目前正在修复一种方法,该方法用于对用户提交的数据进行查询,并通过 SQLITE3 执行数据库操作(例如更新、插入或删除)。

目的是允许接受可选参数,这些参数将引用用户提交的查询变量。如何使用该方法的示例:

incidentkey = request.args.get('incident') incident_rows = databaseInsert2("SELECT * FROM incident_history where incident_number=?", incidentkey)

我提供的代码有几个问题 - 但是,主要问题是我的查询失败。最初查询由于语法而直接失败,但是现在它似乎返回了一个 None 类型的对象,我已经确认可以在 Sqlite3 中手动访问该项目。

有没有更好的方法来处理可能包含未知数量参数的查询?任何帮助将不胜感激。

def databaseInsert2(query, *args): try: conn = sql.connect('db/ccstatus.db') c = conn.cursor() c.execute(query, (args)) conn.commit() c.close() print("Database Insert: Success") except sql.Error as e: print("You have encountered an error while attempting to connect to the database: ", query, args, e)

更新:

我能够使用 *args 作为参数让我的代码按预期工作。我错过了一个没有返回假设结果的关键部分——一旦返回,上面的代码就可以正常工作了。

工作代码示例:

def dbLookup(query, *args): try: con = sql.connect('db/ccstatus.db') con.row_factory = sql.Row c = con.cursor() c.execute(query, (args)) con.commit() rows = c.fetchall() c.close() print("Connection Success") except sql.Error as e: print("You have encountered an error while attempting to connect to the database: ", query, args, e) return rows

如何调用此方法的示例: dbAlter("INSERT INTO systems VALUES (NULL, ?, ?, ?, ?", name, description, urlname, url)

【问题讨论】:

    标签: python python-3.x flask sqlite


    【解决方案1】:

    您可以使用SQLAlchemy 通过 Python 构建查询。

    至于你的代码,第二个参数需要是一个参数元组,即使只有一个参数。

    incident_rows = databaseInsert2("SELECT * FROM incident_history where incident_number=?", (incidentkey,))
    

    【讨论】:

    • 继承了旧系统,运行在过时的 Python (3.5.X) 变体上,并且没有正确的 ORM 设置。为了使用 fstrings,我需要将它们升级到 3.6——我现在正在研究的东西。我还应该补充一点,虽然这将是这个单一查询的解决方案,但它并不能完全回答我将如何使用相同的方法处理不同的查询。例如,假设提供的查询可能具有使用多个数据字段的替代版本,这些字段将传递给 *args。
    • 格式化字符串的方法有很多:pyformat.info不需要使用fstring
    • 我能够使用 *args 作为参数让我的代码按预期工作。我错过了一个没有返回假设结果的关键部分——一旦返回,上面的代码就可以正常工作。不过,谢谢你的帮助,因为你的 cmets 让我找到了问题。 @坚果
    猜你喜欢
    • 1970-01-01
    • 2012-10-27
    • 1970-01-01
    • 1970-01-01
    • 2022-12-02
    • 1970-01-01
    • 1970-01-01
    • 2013-01-15
    • 2022-12-02
    相关资源
    最近更新 更多