Python mySQL - escaping quotes

一笑奈何 提交于 2019-11-27 13:54:35

问题


I have seen this question asked in various ways on this website, but none of them exactly addressed my issue.

I have an sql statement with single quotes inside it, and am trying to use recommended practices before making database queries with it. So the statement is like

val2="abc 'dostuff'" 
sql="INSERT INTO TABLE_A(COL_A,COL_B) VALUES(%s,'%s')" %(val1, val2)
a_cursor.execute(sql)

However, when I run this, I get..

ProgrammingError: (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 'dostuff'.

What am I doing wrong? Thanks very much Nupur


回答1:


Use parameters instead of string interpolation to ensure that your values are properly escaped by the database connector:

sql = "INSERT INTO TABLE_A(COL_A,COL_B) VALUES(%s, %s)"
a_cursor.execute(sql, (val1, val2))

The mysqldb sql parameter style uses the same syntax as used by the python string formatting operator, which is a little confusing.



来源:https://stackoverflow.com/questions/12902862/python-mysql-escaping-quotes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!