【问题标题】:Python and MySQL: passing a list / tuplePython 和 MySQL:传递列表/元组
【发布时间】:2019-01-17 01:50:52
【问题描述】:

我正在用 Python 构建一个查询以传递给 pymysql 查询。

condition=['m']
query = "select * from table where condition in {}'.format(tuple(condition))

我坚持的部分是我想设置脚本以适用于condition 可以是单个项目或多个项目的情况。

在我看来,将列表转换为元组会起作用,但事实并非如此,因为: tuple(condition) 返回: ('m',) ,它无法在我的 mysql 服务器上运行。

什么是最简单的设置方法,我可以将单个值或多个值发送到我在 python 中构建的查询中的where 子句?

【问题讨论】:

    标签: python mysql pymysql


    【解决方案1】:

    使用多个条件的最简单方法是为单个“where”设置格式字符串:

    fmtstr = "select * from table where condition in {} "
    

    还有一些补充:

    addstr = "or condition in {} "
    

    并根据需要连接它们。

    对于您的元组,您可以像使用列表一样处理其中的项目:

    x = (1, 'a')
    x[0] == 1  #evaluates True
    x[1] == 'a'  #same
    

    【讨论】:

      【解决方案2】:

      您可能必须将其作为字符串传递,然后让您的 sql 服务器完成其余的工作。 你试过了吗:

      query = "select * from table where condition in {}'.format(str(tuple(condition)))`
      

      【讨论】:

      • 一旦应用.format()query 将是一个字符串。我认为转换不会改变任何东西。
      【解决方案3】:

      我相信这应该可以解决您的问题:

      condition=['m', 'n']
      
      def quoteWrap(path):
          return '"' + path + '"'
      
      query = "select * from table where condition in ({})".format(','.join([quoteWrap(c) for c in condition]))
      query
      #select * from table where condition in ("m","n")
      

      我还添加了quoteWrap 函数,显然,将您的字符串用引号括起来。

      【讨论】:

      • 嘿,这与我最终得到的结果很接近——没有写函数,而是直接写了(见我的回答)。这是迄今为止最好、最灵活的解决方案。
      【解决方案4】:

      我能想到的另一个技巧是替换查询的最后一部分。

      如果您只有一个元素,通常会出现问题,也就是说,它会在末尾添加一个不必要的逗号,例如 ('m',)

      为什么不这样做:

      condition = ['m']
      queryString = 'SELECT o_id FROM orders WHERE o_k_id IN ' + str(tuple(condition))
      queryString = queryString.replace(',)', ')')
      print(queryString)
      

      所以您的查询将如下所示:

      select * from table where condition in ('m')
      

      如果您必须将多个值传递给您的 where 条件,这仍然适用:

      condition = ['m', 'n']
      queryString = 'select * from table where condition in ' + str(tuple(condition))
      queryString = queryString.replace(',)', ')')
      print(queryString)
      

      输出:

      select * from table where condition in ('m', 'n')
      

      【讨论】:

        【解决方案5】:

        所以我选择了一条不同的路线,因为这些建议要么太麻烦,要么不起作用。

        对我有用的解决方案是: cond = ', '.join('"{0}"'.format(w) for w in condition)

        然后查询是: select * from table where condition in ({}).format(cond)`

        这会生成一串以逗号分隔的值,每个值都用引号括起来。示例:

        condition = ['baseline', 'error']
        cond = ', '.join('"{0}"'.format(w) for w in condition)   
        #"baseline","error"  
        query = select * from table where condition in ({})`.format(cond)   
        # select * from table where condition in ("baseline","error")
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-12-06
          • 2021-08-16
          • 1970-01-01
          • 2016-02-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多