使用 pysqlite 我正在制作一个程序来处理一些数据。对多个表和列中的相似字段进行相同类型的操作,所以我想我可以将sql语句参数化如下所示:
def foo():
column = 'c'
table = 't'
row = 1
# preferred approach, gives syntax error
c.execute('SELECT ? FROM ? WHERE id=?', (column, table, row))
# sanity check, works fine
c.execute('SELECT c FROM t WHERE id=?', (row))
# workaround, also works, but is this the right way?
c.execute('SELECT % FROM % WHERE id=?' % (column, table), row))
我得到的错误不是很有帮助(sqlite3.OperationalError: near "?": syntax error
),但我明白了:Pysqlite 不喜欢以这种方式使用占位符。
谁能指出这里发生了什么以及执行上述操作的正确方法?