字符串格式化时Python sqlite3操作错误?

时间:2012-08-20 02:34:25

标签: python sqlite string-formatting

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

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只接受?运营商吗?或者有什么东西我正在捣乱?

2 个答案:

答案 0 :(得分:3)

您正在尝试替换元数据,但遗憾的是参数化查询无效。您必须在此处使用插值等,但确保该值已清理;这是SQL注入的可能向量

cur.execute("SELECT * FROM %s" % (total[0],))

答案 1 :(得分:2)

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