python运行mysql语句报错怎么解决

王林
王林 转载
2023-05-29 13:34:06 1263浏览

一 python 运行mysql 语句报错

众所周知,python有转译机制 %s和%d都会被转译成字符串或数字,而sql的模糊查询也需要用到%,都进行模糊查询时,刚好查询条件还是个变量那就很尴尬了。

解决方法其实很简单,把需要进行模糊查询的字符串从sql中单独拎出来进行拼接就好

错误方式

shopId = "zbw_010002"
'''select * from base_saleflows where shopId='{0}' and card_id is not NULL and standard_cls4 like "%湿巾%" '''.format(shopId)

发现 不对,这样的语句 mysql是运行不了的。

python运行mysql语句报错怎么解决

args='%湿巾%'shopId = "zbw_010002"mysql_sentence='''select a.shopId, a.sale_money,a.card_id ,a.standard_cls4 from base_saleflows a join  base_vips b on a.card_id = b.card_id where a.shopId='{0}' and a.card_id is not NULL and a.standard_cls4 like '{1}' '''.format(shopId,args)print(mysql_sentence)

结果为

select * from base_saleflows a join  base_vips b on a.card_id = b.card_id where a.shopId='zbw_010002' and a.card_id is not NULL and a.standard_cls4 like '%湿巾%'

二 字符串分组拼接

对 cls3列 按照流水号flow_no 进行 分组拼接字符串,拼接符号为‘-’

#  分组拼接result = vipsaleflow_common.pivot_table(values='standard_cls3',index='flow_no',aggfunc=lambda x:x.str.cat(sep='-'))

python运行mysql语句报错怎么解决

应用 :按照 年 ,季度 , 分店号 ,湿巾类型) 分组 求每个季度新客数

四 根据时间戳衍生 年 月 季度

saleflow['oper_date']=saleflow['oper_date'].astype(str)  #字符串saleflow['oper_date'] = saleflow.oper_date.apply(lambda x:datetime.strptime(x, '%Y-%m-%d %H:%M:%S'))saleflow["month"] = saleflow.oper_date.map(lambda x: x.month)saleflow["year"] = saleflow.oper_date.map(lambda x: x.year)#https://www.it1352.com/584941.htmllookup = {1: 1, 2: 1,3: 1,4: 2, 5: 2, 6: 2, 7: 3,8: 3,9: 3,10: 4, 11: 4,12: 4}saleflow['Season'] = saleflow['oper_date'].apply(lambda x: lookup[x.month]) saleflow['YearMonth'] = saleflow['oper_date'].map(lambda x: 100*x.year + x.month)

以上就是python运行mysql语句报错怎么解决的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:亿速云,如有侵犯,请联系admin@php.cn删除