简单的Select查询中的Python sqlite3 OperationalError

时间:2013-01-18 14:59:20

标签: python sqlite

我在sqlite(python sqlite3)中有一个非常简单的查询有一个奇怪的行为

这是一个有效的查询

cursor = self.con.cursor()
cursor.execute("SELECT * FROM vpro1 ORDER BY :orderby DESC LIMIT 1", {"table": "vpro1", "orderby": self.unit_timestamp})

但是这个给我一个错误

cursor = self.con.cursor()
cursor.execute("SELECT * FROM :table ORDER BY :orderby DESC LIMIT 1", {"table": "vpro1", "orderby": self.unit_timestamp})

例外是

sqlite3.OperationalError: near ":table": syntax error

所以,当我尝试使用qmark表名时,它会抛出一个错误,如果我在查询中对其进行硬编码,它的工作原理是:orderby适用于我使用的任何内容(qmark,hardcoded,named)...同样的行为与qmark风格(?,?带元组)

感谢您的建议!

1 个答案:

答案 0 :(得分:2)

您无法使用DB API来填写表名。我不确定这是什么原因,但我过去遇到过同样的问题。它不适用于SQLite或MySQL,也可能不适用于其他人。

有关解决方法,请参阅Donald Miner对其他问题的回答。

def scrub(table_name):
    return ''.join( chr for chr in table_name if chr.isalnum() )

scrub('); drop tables --')  # returns 'droptables'

然后将其作为格式字符串传递。

table = "vpro1"
cursor.execute("SELECT * FROM {0} ORDER BY :orderby DESC LIMIT 1".format(scrub(table)), {"orderby": self.unit_timestamp})