前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >解决python3插入mysql时内容带有引号的问题

解决python3插入mysql时内容带有引号的问题

作者头像
砸漏
发布2020-11-05 15:16:46
2.4K0
发布2020-11-05 15:16:46
举报
文章被收录于专栏:恩蓝脚本恩蓝脚本

插入mysql时,如果内容中有引号等特殊符号,会报错,

解决方法可以用反斜杠转义,还可以用pymysql的一个方法自动转义:

c = ”’  北京时间9月20日晚间9点半,智能供应链服务供应商百世集团将在<a class=”wt_article_link” onmouseover=”WeiboCard.show(2125973432,’tech’,this)” href=”?zw=tech” rel=”external nofollow” target=”_blank” 纽约证券交易所</a 正式挂牌上市,交易代码为“BSTI”。这是继<span id=”usstock_ZTO” <a href=”http://stock.finance.sina.com.cn/usstock/quotes/ZTO.html” rel=”external nofollow” class=”keyword f_st” target=”_blank” 中通</a </span <span id=quote_ZTO </span 快递之后第二家赴美上市的快递物流企业。&nbsp;</p <p   此次IPO百世集团一共发行4500万股美国存托股份(ADS),每股价格为10美元,总融资额高达4.5亿美元,为今年目前为止在美国上市的中国公司中募资规模最大的IPO。此外,百世和售股股东还允许其承销商通过超额配售权购买额外不多于675万股ADS。</p <p   有中通这个“珠玉”在前,美股市场似”’

pymysql.escape_string(c)

sql = “INSERT INTO tbl_stream_copy(weburl,title,content,channelId,datetime,pubtime,website)VALUES (‘%s’,’%s’,\’%s\’,’%s’,’%s’,’%s’,’%s’)” % (a,b,pymysql.escape_string(c),e,datetime,datetime,a)

补充拓展:Python中执行MySQL语句, 遇到同时有单引号, 双引号处理方式 !r, repr()

SQL语句:

代码语言:javascript
复制
insert_cmd = "INSERT INTO {0} SET {1}"
.format(db_conn.firmware_info_table, 
  ','.join(['{0}={1!r}'.format(k, str(v)) for (k, v) in info_dict.items()]))

其中{0}={1!r} 作用是设置字段的值,一般情况应该是:

{0}='{1}’.format(columnA, value)

但若value中同时有双引号和单引号(“”, ”),比如{‘abc’: ‘123’, “def”: “456”},

则会在execute(insert_cmd)时报错。

如果想保持数据原始性,不使用replace替换成统一的单引号或者双引号,

则可以使用!r来调用repr() 函数, 将对象转化为供解释器读取的形式。

repr() 返回一个对象的 string 格式。

!r 表示使用repr()替代默认的str()来返回。

注:repr是str的方法,所以value需要是string,若数据是dict等类型,需要使用str()转换成string

According to the Python 2.7.12 documentation: !s (apply str()) and !r (apply repr()) can be used to convert the value before it is formatted.

贴出str类中的repr说明:

repr(object) Return a string containing a printable representation of an object. This is the same value yielded by conversions(reverse quotes). It is sometimes useful to be able to access this operation as an ordinary function. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a __repr__() method.

以上这篇解决python3插入mysql时内容带有引号的问题就是小编分享给大家的全部内容了,希望能给大家一个参考。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-09-11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
云数据库 MySQL
腾讯云数据库 MySQL(TencentDB for MySQL)为用户提供安全可靠,性能卓越、易于维护的企业级云数据库服务。其具备6大企业级特性,包括企业级定制内核、企业级高可用、企业级高可靠、企业级安全、企业级扩展以及企业级智能运维。通过使用腾讯云数据库 MySQL,可实现分钟级别的数据库部署、弹性扩展以及全自动化的运维管理,不仅经济实惠,而且稳定可靠,易于运维。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档