0

我有这个小的装饰器函数,我将在表中找到未知数量的条目:

def Deco(func):
     func
     conn = sqlite3.connect('/home/User/vocab_database/vocab.db')
     with conn:
         cur = conn.cursor()
         cur.execute("SELECT name FROM sqlite_master WHERE type='table'")
         total = cur.fetchall()
         print "You have %d tables " % len(total)

       ## this line below, is where I wanted to use a formatted string ##
         cur.execute("SELECT * FROM %s") % total[0]
         entries = cur.fetchall()
         print "You have %d entries" % len(entries)

然后我收到此错误消息:

Traceback (most recent call last):
  File "./database_trial.py", line 19, in <module>
    class Vocab:
  File "./database_trial.py", line 25, in Vocab
    @Deco        
  File "./database_trial.py", line 15, in Deco
    cur.execute("SELECT * FROM %s") % total[0]
sqlite3.OperationalError: near "%": syntax error

sqlite3 只接受?运算符吗?还是我在搞砸什么?

4

2 回答 2

3

您正在尝试替换元数据,所以很遗憾,参数化查询不起作用。您必须在此处使用插值或类似方法,但请确保该值已被清理;这是一个可能的 SQL 注入向量

cur.execute("SELECT * FROM %s" % (total[0],))
于 2012-08-20T02:54:45.460 回答
2

在该行cur.execute("SELECT * FROM %s") % total[0]中,您将%运算符应用于cur.execute调用结果。我认为您想在通话中进行替换,例如cur.execute("SELECT * FROM ?", (total[0],)).

于 2012-08-20T02:36:25.020 回答