使用 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 不喜欢以这种方式使用占位符。
谁能指出这里发生了什么以及执行上述操作的正确方法?
您根本不能对列名或表名使用占位符。我对此没有权威的引用——我只是通过尝试和失败才“知道”这一点。不过,这还是有一定道理的:
- 如果列和表可以参数化,那就没什么了
准备的目的(
execute
-ing) 获取之前的 SQL 语句,因为该语句的所有部分都可以是
更换。
- I'm not sure about pysqlite1, but MySQLdb automatically quotes all
string parameters. Column and table names should not be quoted. So it
would complicate the parsing required by the driver if it had to
decide if a placeholder represented a column or table name versus a
value that needs quoting.
简而言之,您找到了正确的方法——使用字符串格式。
c.execute('SELECT {} FROM {} WHERE id=?'.format(column, table), row))
1 Not all drivers quote parameters -- oursql
doesn't, since it sends SQL and arguments to the server separately.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)