【问题标题】:Python-list in the query查询中的 Python 列表
【发布时间】:2012-03-20 13:00:23
【问题描述】:

我正在使用 python 插件。我使用列表来存储一些值,如下所示:

known_stn.append('1')
known_stn.append('2')

我的查询是

query=("SELECT survey, station FROM stat WHERE stat.station IN (%s) AND station.survey = '2011410'" %known_stn)

WHERE station.station IN (['1', '2']) 发生错误,因为列表包含 [] 括号。 我尝试替换那些括号,但它们没有被替换。

还有其他数据结构可以使用吗?或者出路替换方括号...

【问题讨论】:

  • “Python 插件”没有任何意义。您使用什么来与 SQL 交互?
  • 我使用 postgresSQL 作为数据库。和 pyqt4 设计器用于 GUI .....
  • 不要自己格式化查询字符串;这要求进行 SQL 注入攻击。在用于执行查询的任何内容中使用内置格式。 (以下答案是正确的,因为您需要先将列表加入字符串。)
  • 例如,在任何使用Python Database API的模块中,您应该写cursor.execute(query, parameters)

标签: python plugins


【解决方案1】:

您需要先将列表转换为字符串:

>>> my_list = [1,2,3]
>>> str(my_list)
'[1, 2, 3]'
>>> map(str, my_list)
['1', '2', '3']
>>> ','.join(map(str, my_list))
'1,2,3'
>>> 'select ... where foo in (%s)' % ','.join(map(str, my_list))
'select ... where foo in (1,2,3)'

【讨论】:

    【解决方案2】:

    您需要在将列表替换为模板字符串之前将其格式化为字符串

    "where (%s) blah" % ', '.join(map(str,known_stn))
    

    http://docs.python.org/library/stdtypes.html#str.join

    map(str,known_stn) 在加入之前将元素本身转换为字符串。

    另外,请注意有关 SQL 注入的警告。

    【讨论】:

      猜你喜欢
      • 2016-07-21
      • 1970-01-01
      • 1970-01-01
      • 2020-11-30
      • 1970-01-01
      • 1970-01-01
      • 2020-10-15
      • 2017-02-05
      • 2021-04-18
      相关资源
      最近更新 更多