pyodbc - How to perform a select statement using a variable for a parameter

孤者浪人 提交于 2019-11-27 04:52:11

Without knowing the type of the column DeviceName and what database server, I would quote the string that is being used to constrain DeviceName

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

and see what happens.

You are also able to parameterize statements:

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

This a better approach for the following reasons:

  • Protection against SQL injection (you should always validate user input regardless of whether parameterized or dynamic SQL is used)
  • You don't have to worry about escaping where clause values with single quotes since parameters are passed to the database separately
  • SQL is prepared once, subsequent executions of the query use the prepared statement instead of recompiling
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!