How can I escape the input to a MySQL db in Python3?

前端 未结 3 927
说谎
说谎 2021-01-04 09:36

How can I escape the input to a MySQL db in Python3? I\'m using PyMySQL and works fine, but when I try to do something like:

cursor.execute(\"SELECT * FROM `         


        
3条回答
  •  Happy的楠姐
    2021-01-04 09:41

    Although the "solved" answer works, it is not best practice. When using a library conforming to the Python DBI, you should be using bind variables rather than formatting a string and passing it to execute. There are dangers inherent in that methodology.

    Therefore, this is the right way to do it:

    cursor.execute("SELECT * FROM `Codes` WHERE `ShortCode` = %s", text)
    

    Note that this is not a format string but a bind variable passed to the executing cursor.

    For details: Python DBI PEP

提交回复
热议问题