pymysql 插入数据 转义处理

首页 / 新闻资讯 / 正文

liramail_dribbble

最近用pymysql把一些质量不是很高的数据源导入mysql数据库的时候遇到一点问题,主要是遇到像 \ 这样的具有特殊意义的字符时比较难处理。这里有一个解决方案

python3
pymysql
linux

插入(查询)数据时遇到一些特殊字符会使得程序中断。操作失败。比如 \这样的转义字符

插入(查询)之前用 connection.escape(str)处理一下即可

import pymongo  sql_pattern = "select * from my_collection where name = %s" #注意,这里直接用%s,不要给%s加引号,因为后面转移过后会自动加引号 name = "xxx\xxx" name = connection.escape(name) sql = sql_pattern%name print(sql) # select * from my_collection where name = 'xxx\\xxx'  with connection.cursor() as cursor:     try:         cursor.execute(sql)     except:         print(sql)         pass     for r in cursor:         print(r)