Python:在查询中将列表变量作为参数传递

时间:2018-08-30 21:28:32

标签: python sql

要求是将列表中的参数传递给python代码中存在的sql查询

parmlist.py
  
sale_call = [12,88]
yr_range = [2015,2016,2017,2018]
    


Codefile.py

     conn = <connecting to MySQL>
    
     cursor = conn.cursor()

cursor.execute(‘Insert into sales_repo select distinct a.yr_sll from cust_data a join proc_data b 
On a.prd_key = b.prd_key where b.range1=?,b.range2=?,b.range3=? and b.yr in ?’)

我做了以下事情:

cursor.execute(‘Insert into sales_repo select distinct a.yr_sll from cust_data a join proc_data b 
On a.prd_key = b.prd_key where b.range1=?,b.range2=?,b.range3=? and b.yr in ?’ ,parmist.sale_call[0],parmist.sale_call[1],parmist.yr_range[3])
    


但是parmist.yr_range[3]似乎正在进入2018年。 而不是完整列出yr_range = [2015,2016,2017,2018]

它只是取最后一个值,即2018

如何在查询中将整个列表作为变量传递?

Update_1:

我尝试了以下操作:

sale_call = [12,88]
yr_range = [2015,2016,2017,2018]

cursor.execute(‘Insert into sales_repo select distinct a.yr_sll from cust_data a join proc_data b 
On a.prd_key = b.prd_key where b.range1=?,b.range2=?,b.range3=? and b.yr in (' + ','.join(map(str, yr_range))’)

当我尝试通过python代码执行上述操作时,以上操作无效。但是在使用熊猫作为时执行:

pd.read_sql_query(‘Insert into sales_repo select distinct a.yr_sll from cust_data a join proc_data b 
    On a.prd_key = b.prd_key where b.range1=?,b.range2=?,b.range3=? and b.yr in (' + ','.join(map(str, yr_range))’,conn)

任何提示为什么它不起作用?

1 个答案:

答案 0 :(得分:2)

我认为该错误只是您格式化查询字符串的方式中的某处。在这两种情况下似乎都错了,但是也许熊猫查询正在处理它。这使查询更容易遵循。

如果在<div id="ifr1"></div>子句中将<VirtualHost *:443> ServerName www.yoursite.com DocumentRoot /var/www/site SSLEngine on SSLCertificateFile /path/to/www_yoursite_com.crt SSLCertificateKeyFile /path/to/www_yoursite_com.key SSLCertificateChainFile /path/to/DigiCertCA.crt </VirtualHost> 用作?值,则需要指定参数。我将它们取出是因为我不确定您打算如何使用它们。 b.range函数将字符串中的WHERE替换为以逗号分隔的字符串值的年份。

.format()
相关问题