mysql-connector python 'IN' operator stored as list

穿精又带淫゛_ 提交于 2019-12-07 06:02:48

问题


I am using mysql-connector with python and have a query like this:

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

NOw, if my variable 'dc' is a list like this:

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

Then I have a mysql query like below:

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

My question is, how do I write this query in my python code which will convert my variable 'dc' to a list?

I tried the below query but getting error: Failed processing format-parameters; 'MySQLConverter' object has no attribute '_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))

Can somebody please tell me what I am doing wrong?

Thanks in advance


回答1:


I'm not familiar with mysql-connector, but its behavior appears to be similar to MySQLdb in this regard. If that's true, you need to use a bit of string formatting:

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)


来源:https://stackoverflow.com/questions/17847297/mysql-connector-python-in-operator-stored-as-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!