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

前端 未结 3 911
说谎
说谎 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条回答
  •  一生所求
    2021-01-04 10:01

    Solved. In PyMySQL the right way is like this:

    import pymysql
    import sys
    conn = pymysql.connect(host="localhost",
                user="test",
                passwd="",
                db="test")
    cursor = conn.cursor()
    text = conn.escape(request[1])
    cursor.execute("SELECT * FROM `Codes` WHERE `ShortCode` =  {}".format(text))
    
    cursor.close()
    conn.close()
    

    Where the text = conn.escape(request[1]) line is what escapes the code. Found it inside PyMySQL code. There, request[1] is the input.

提交回复
热议问题