Python torndb(MySQLdb)查询参数不工作
像这样:Python torndb(MySQLdb)查询参数不工作,python,mysql,mysql-python,Python,Mysql,Mysql Python,像这样: In [43]: conn.query('select %s from topic order by %s limit 2', 'id', 'id desc') Out[43]: [{'id': u'id'}, {'id': u'id'}] In [44]: conn.query('select id from topic order by id desc limit 2') Out[44]: [{'id': 10L}, {'id': 9L}] 为什么结果不一样?这是因为MySQLd
In [43]: conn.query('select %s from topic order by %s limit 2', 'id', 'id desc')
Out[43]: [{'id': u'id'}, {'id': u'id'}]
In [44]: conn.query('select id from topic order by id desc limit 2')
Out[44]: [{'id': 10L}, {'id': 9L}]
为什么结果不一样?这是因为MySQLdb驱动程序将查询参数插入查询的方式不同 第一个查询实际转换为(注意引号):
'id'
这里是一个字符串,不是列名。谢谢,如何解决这个问题并获得正确的结果?@Gee好吧,一个选项是使用字符串格式,但不推荐使用;在这种情况下,请确保您确实信任列名和order by子句的源:conn.query('select%s from topic order by%s limit 2'('id',id desc'))
。是的,您是对的,%s
只能通过变量使用
select 'id' from topic order by 'id desc' limit 2