解决Python3插入MySQL时内容带有引号的问题
本文详解在Python3中将包含单双引号的内容插入MySQL数据库时引发的报错问题。提供两种解决方案:使用pymysql的escape_string方法自动转义,以及在SQL字符串格式化中使用!r调用repr()函数。通过具体代码示例展示如何正确处理特殊字符,确保数据完整入库。
MySQL插入含引号数据报错原因
在向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>快递之后第二家赴美上市的快递物流企业。 </p> <p> 此次IPO百世集团一共发行4500万股美国存托股份(ADS),每股价格为10美元,总融资额高达4.5亿美元,为今年目前为止在美国上市的中国公司中募资规模最大的IPO。此外,百世和售股股东还允许其承销商通过超额配售权购买额外不多于675万股ADS。</p> <p> 有中通这个“珠玉”在前,美股市场似'''
使用pymysql.escape_string自动转义
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格式符处理复杂引号
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()函数的作用是返回一个对象的字符串表示形式。
!r 表示在格式化时调用repr()替代默认的str()来生成返回值。
注意:repr是str类的方法,因此value参数需要是字符串类型;若数据为dict等其他类型,需先使用str()将其转换为字符串。
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时内容带有引号问题的方法即为完整解决方案,希望能对读者有所帮助。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









