最近做爬蟲數據抓取的時候遇到一個,抓取回來的內容含有python的轉義字符,導致在寫入mysql的時候一直報錯,嘗試通過Unicode編碼,發現Unicode編碼后也含有\轉義字符,導致拼接sql的語句在執行mysql寫入時候依然報錯,請教大神嘗試 “”,”“”“”“,字符串前面加r,限制轉義,當執行插入(查詢)數據時遇到一些特殊字符會使得程序中斷。操作失敗。問題還是無法解決。
解決辦法
插入(查詢)之前用 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)
問題完美解決。