2012-03-01 103 views
8

我想遍历表中的所有行命名吞吐量,但对于特定的DeviceName(我已经存储在数据['DeviceName']]我已经试过以下,但它不工作:pyodbc - 如何使用参数执行一个选择语句使用变量

for row in cursor.execute("select * from Throughput where DeviceName=%s"), %(data['DeviceName']): 

编辑:也尝试过这一点,但它不工作:

for row in cursor.execute("select * from Throughput where(DeviceName), values(?)", (data['DeviceName'])): 

EDIT2:我的最终工作代码片段:

query = "select * from Throughput where DeviceName = '%s'" % data['Device Name'] 
     try: 
      for row in cursor.execute(query): 
+0

“不工作”怎么样?你收到什么错误或意外的行为? – Andy 2012-03-01 15:17:49

回答

-11

不知道列设备名称,什么数据库服务器的类型,我想引用正被用来限制设备名称

"select * from Throughput where DeviceName='%s'" % data['DeviceName'] 

,并看看会发生什么的字符串。

+0

谢谢。这就是诀窍! – Parth 2012-03-01 15:45:20

+6

如果data ['DeviceName']'是以任何方式(直接或间接)由用户提供的,那么您只是打开自己的SQL注入攻击。或者devicename使用引号,这只是打破。 *并且*效率低下,因为驱动程序无法为SQL语句重新使用准备好的查询计划。 – 2015-01-10 13:41:20

33

你也能parameterize声明:

... 
cursor.execute("select * from Throughput where DeviceName = ?", data['DeviceName']) 
... 

这出于以下原因一个更好的方法:

  • 针对SQL注入防护(你应该总是验证用户输入无论参数还是使用动态SQL)
  • 由于参数分别传递到数据库,您不必担心使用单引号转义where子句值
  • SQL准备一次查询的后续执行使用事先准备好的声明,而不是重新编译
+0

当这样做时,有没有什么办法可以打印出整个查询,因为我有日期/时间转换错误,但我不知道在哪里,但是,当我打印出查询字符串时,它会显示问号而不是应该取代这些问号的实际值。如果你可以看看我的问题http://stackoverflow.com/questions/37861319/pyodbc-cursor-execute-wont-insert-parameters-into-sql-string?noredirect=1#comment63185389_37861319我真的很感激它。 – 2016-06-16 16:53:48

+0

@ M.Barbieri,在MySQL中启用日志记录以查看实际执行的语句。 – DrDamnit 2017-06-19 19:15:29