pymysql 插入数据 转义处理

2022年12月31日10:57:52

最近用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)

  • 作者:匿名姐姐
  • 原文链接:https://blog.csdn.net/u013075468/article/details/51455745
    更新时间:2022年12月31日10:57:52 ,共 503 字。