pyodbc-如何使用参数变量执行select语句

2024-09-30 18:16:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图遍历名为Throughput的表中的所有行,但针对特定的设备名(我已将其存储在data['DeviceName']中)。我试过以下方法,但不起作用:

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):

Tags: 方法infrom编辑forexecutedatawhere
2条回答

您还可以parameterize语句:

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

这是一种更好的方法,原因如下:

  • 针对SQL注入的保护(无论使用的是参数化的还是动态的SQL,都应始终验证用户输入)
  • 不必担心用单引号转义where子句值,因为参数是分别传递给数据库的
  • SQL只准备一次,查询的后续执行使用prepared语句而不是重新编译

在不知道列DeviceName的类型和数据库服务器的情况下,我将引用用于约束DeviceName的字符串

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

看看会发生什么。

相关问题 更多 >