参数绑定不适用于SQLite PRAGMA table_info

时间:2016-10-11 19:52:49

标签: parameterbinding

我正在使用sqlite3 for Python。为什么不对表达式使用参数绑定:

select p.*
from person_log p 
join (select first_name,last_name
      from person_log
      group by first_name,last_name
      having count(*) >=2 and count(distinct action) >= 2) p1
on p1.first_name=p.first_name and p1.last_name=p.last_name

如预期的那样?对于任何其他self.cursor.execute("PRAGMA table_info(?)", table_name) 查询,它会按预期替换我的参数。我现在用

SELECT

但这对SQL注入是不安全的。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

我想做同样的事情,但它看起来像it's not possible to bind parameters to Sqlite PRAGMAs

你可以做些什么来保持安全(以及我最终可能做的事情)是在SQL中query all the table names in the current Sqlite database,如下所示:

SELECT * FROM sqlite_master

或者,只是获取表并忽略视图,请执行:

SELECT * FROM sqlite_master where type="table"

然后将这些表名存储在数组/列表/集中。现在您已经拥有了db中所有可能表的列表,您只需检查用户输入以查看它是否与数组中的某个表匹配。如果是这样,那么直接插入字符串是安全的,并且没有机会进行SQL注入。从本质上讲,它正在针对白名单进行消毒。

在Python中,它看起来像这样:

if table_name in tables:
    self.cursor.execute("PRAGMA table_info('%s')" % table_name)
else:
    print("Bad table name: %s" % table_name)

答案 1 :(得分:0)

对于在此问题上发生的任何人,最佳方法是使用像这样的编译功能:

self.cursor.execute("SELECT * FROM pragma_table_info(?)", table_name)

sqlite3_prepare_v2( db, "SELECT * FROM pragma_table_info(?)", -1, &stmt, &tail );
sqlite3_bind_text( stmt, 1, table_name, -1, nullptr );
相关问题