描述: 最近在爬取数据保存到数据库时,遇到有引号的字符串插入MySQL报错:1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near
转义字符串解决
方法一 :
python"># 处理字符串中的引号
def handle_quotation_marks(value):if "'" in value:value = value.replace("'", "\\'")if '"' in value:if value[0] == '"' and value[-1] == '"':value = value[1:-1]else:value = value.replace('"', '\\"')return value
调用如下:
python">if __name__ == '__main__':my_title = "我是'单引号'," + '"我是双引号"'# 换行打印 f是格式化字符串(拼接字符串),和C# $格式化字符串的使用方法是一样的print(f"\n{handle_quotation_marks(my_title)}")
方法二 :
调用PyMySQL的escape_string方法,escape_string是专门用来转义处理特殊字符串的
安装PyMySQL库
pip install PyMySQL
调用如下
python">from pymysql.converters import escape_stringif __name__ == '__main__':my_title = "我是'单引号'," + '"我是双引号"'print(f"\n{escape_string(my_title)}")
参考资料:
https://blog.csdn.net/Love_Story_Boyslove/article/details/124703448