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

王林
发布: 2023-05-29 13:34:06
转载
2344人浏览过

一  python 运行mysql 语句报错

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

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

错误方式

shopId = "zbw_010002"<br/>'''select * from base_saleflows where shopId='{0}' and card_id is not NULL and standard_cls4 like "%湿巾%" '''.format(shopId)
登录后复制

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

立即学习Python免费学习笔记(深入)”;

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)<br/>
登录后复制

结果为

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中文网其它相关文章!

python速学教程(入门到精通)
python速学教程(入门到精通)

python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
相关标签:
来源:亿速云网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 //m.sbmmt.com/ All Rights Reserved | php.cn | 湘ICP备2023035733号