当前位置:首页 » python运维 » 正文

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

看: 1032次  时间:2020-08-09  分类 : python运维

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

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

c = '''  北京时间9月20日晚间9点半,智能供应链服务供应商百世集团将在纽约证券交易所正式挂牌上市,交易代码为“BSTI”。这是继中通快递之后第二家赴美上市的快递物流企业。 


  此次IPO百世集团一共发行4500万股美国存托股份(ADS),每股价格为10美元,总融资额高达4.5亿美元,为今年目前为止在美国上市的中国公司中募资规模最大的IPO。此外,百世和售股股东还允许其承销商通过超额配售权购买额外不多于675万股ADS。


  有中通这个“珠玉”在前,美股市场似'''

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语句:

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时内容带有引号的问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持python博客。

<< 上一篇 下一篇 >>

搜索

推荐资源

  Powered By python教程网   鲁ICP备18013710号
python博客 - 小白学python最友好的网站!