【问题标题】:mysql-connector python 'IN' operator stored as listmysql-connector python 'IN' 运算符存储为列表
【发布时间】:2013-07-24 17:07:03
【问题描述】:

我正在使用 mysql-connector 和 python 并有这样的查询:

SELECT avg(downloadtime) FROM tb_npp where date(date) between %s and %s and host like %s",(s_date,e_date,"%" + dc + "%")

现在,如果我的变量 'dc' 是这样的列表:

 dc = ['sjc','iad','las']

然后我有一个如下的mysql查询:

SELECT avg(downloadtime) FROM tb_npp where date(date) = '2013-07-01' and substring(host,6,3) in ('sjc','las');

我的问题是,如何在我的 python 代码中编写这个查询,它将我的变量 'dc' 转换为一个列表?

我尝试了以下查询,但出现错误:处理格式参数失败; 'MySQLConverter' 对象没有属性 '_list_to_mysql'

cursor3.execute("SELECT avg(downloadtime) FROM tb_npp where date(date) between %s and %s and substring(host,6,3) in %s",(s_date,e_date,dc))

谁能告诉我我做错了什么?

提前致谢

【问题讨论】:

  • 如果您只运行查询而不使用 python 是否有效?
  • 是的,查询正确

标签: python mysql mysql-connector


【解决方案1】:

作为@unutbu 特定于使用 mysql-connector 的答案的替代方案:

cursor.execute(
    "SELECT thing "
    "    FROM table "
    "    WHERE some_col > %(example_param)s " 
    "    AND id IN ({li})".format(li=", ".join(list_of_values)),
    params={
        "example_param": 33
    })

如果您尝试将加入的列表移动到参数中(例如示例参数),它可能 抱怨是因为 mysql-connector 将值解释为字符串。

如果您的列表不是由默认的字符串格式(如整数)组成,那么在您的连接语句中将 list_of_values 替换为:

[str(v) for v in list_of_values]   

【讨论】:

    【解决方案2】:

    我不熟悉 mysql-connector,但在这方面它的行为似乎是 similar to MySQLdb。如果是这样,您需要使用一些字符串格式:

    sql = """SELECT avg(downloadtime) FROM tb_npp where date(date) = %s 
             and substring(host,6,3) in ({c})""".format(
                c=', '.join(['%s']*len(dc)))    
    args = ['2013-07-01'] + dc
    cursor3.execute(sql, args)
    

    【讨论】:

    • 哈.. 非常感谢.. :) 它可以工作,但是如果我有很多 args,我可以将它们全部连接到 args 变量,例如:args = ['2013-07 -01'] + ['2013-07-07'] + 直流?
    • 是,或者:args = ['2013-07-01', '2013-07-07'] + dc
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-11
    • 2016-12-22
    • 1970-01-01
    • 2018-04-15
    • 2018-06-14
    • 2016-03-14
    相关资源
    最近更新 更多