[Python] MySQLdb 遇到 escape string 解法


今天在用 Python 的 MySQLdb 來 UPDATE 資料遇到

_mysql_exceptions.ProgrammingError: (1064, 'You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near \'... at line 1')



如上語法為

sql = "UPDATE wp_posts SET post_title='{}',post_content='{}' WHERE ID=12345".format(newTitle, newData)
cursor.execute(sql)

newData 裡面有單引號( ' )也有雙引號( " )

這時候就會遇到類似 SQL injection 的問題

解決方法和 Node.js 類似

直接使用 MySQLdb 的 library


sql = "UPDATE wp_posts SET post_title=%s,post_content=%s WHERE ID=12345"
cursor.execute(sql, (newTitle, newData))

解決!不用再擔心 escape string 了!!!


後記:
我認為用第一種寫法是很容易想到的寫法
畢竟直接跑 SQL 語法就長這樣啊
心得是不管是 Node.js 還是 Python 還是什麼程式語言
如果有 library 可以用就不要自己處理字串
還可以避免 SQL injection


reference:
https://stackoverflow.com/questions/3617052/escape-string-python-for-mysql

留言

熱門文章