【问题标题】:Sqlite unrecognized token: "'''"Sqlite 无法识别的令牌:“'''”
【发布时间】:2016-02-04 05:53:33
【问题描述】:

我在 python 中使用 sqlite3 时遇到了问题。

def getEntryId(self, table, field, value, createNew=True):
    cur=self.con.execute("select rowid from %s where %s = '%s'" % (table, field, value))
    res=cur.fetchone()
    if res==None:
        cur=self.con.execute("insert into %s (%s) values('%s') " % (table, field, value))
        return cur.lastrowid
    else:
        return res[0]

但是,我遇到了这个: OperationalError:无法识别的令牌:“'''”。看来我的第二行代码不正确。 我不知道为什么,所以我做了同样的事情:

cu.execute("select rowid from urllist where %s = '%s'" % ('url', 'yes'))

它没有出现错误。为什么?我该如何解决?

【问题讨论】:

  • 很可能,您有一个 Bobby Tables 的亲戚访问您的程序,输入撇号表示您的值。

标签: python sqlite


【解决方案1】:

您应该对查询进行参数化。虽然不能参数化表和字段名称,但可以使用字符串格式将表和字段名称插入查询中,但请确保您信任源或正确验证值:

query = "select rowid from {table} where {field} = %s".format(table=table, field=field)
cur = self.con.execute(query, (value, ))
res = cur.fetchone()

参数化不仅有助于防止SQL injection攻击,还可以处理数据类型转换,正确转义参数,也可以解决您当前的问题。

【讨论】:

  • 我在更改后遇到了 OperationalError: near "%": syntax error on cur = self.con.execute(query, (value, ))。这是为什么呢?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-17
  • 1970-01-01
  • 2018-10-29
  • 2016-11-25
  • 1970-01-01
相关资源
最近更新 更多