传递正确的SQL语句-正确的方法是什么?

时间:2019-03-12 07:35:26

标签: python flask psql

我的代码正在关注

selection_option_heading_1 = request.form.get("selection_option_heading").lower()
search_string_1 = request.form.get("search_string").lower()
search_string_1 = ("'%"+search_string_1+"%'")
check_books_in_db = db2.execute(f"SELECT isbn, title, author, year FROM books WHERE {selection_option_heading_1} ILIKE {search_string_1} LIMIT 50").fetchall()
return (check_books_in_db)

正在工作。

但是我知道应该有适当的方法来做到这一点。有帮助吗?

1 个答案:

答案 0 :(得分:0)

通常,您不会像这样将用户输入直接注入SQL语句,因为这会使您的代码容易受到sql注入攻击。如果使用python执行SQL查询,则标准mysql.connector库提供了相对安全的基于用户输入执行查询的方法。

由于selection_option_heading_1是列名,因此最好在查询之前检查该列是否存在。

一个例子是:

SQL_col_query = "SELECT * FROM information_schema.columns
                 WHERE table_schema = 'your_schema'
                 AND table_name   = books"
cur.execute(SQL_col_query)
column_names = [row[0] for row in cur.fetchall()]
if ( selection_option_heading_1 in column_names) :
    SQL_query = f"SELECT isbn, title, author, year FROM books WHERE {selection_option_heading_1} ILIKE %S LIMIT 50"
    data = (selection_option_heading_1 , search_string_1 )
    cur.execute(SQL_query , data)
    ...

这绝对是您正在做的事情的更安全的选择,但是我不确定这是否是执行此类查询的最佳方法。

相关问题