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

前端 未结 3 910
说谎
说谎 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 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

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-04 10:06

    Ready to use helper function

    def mysql_insert(conn, table, row):
        cols = ', '.join('`{}`'.format(col) for col in row.keys())
        vals = ', '.join('%({})s'.format(col) for col in row.keys())
        sql = 'INSERT INTO `{0}` ({1}) VALUES ({2})'.format(table, cols, vals)
        conn.cursor().execute(sql, row)
        conn.commit()
    

    Usage example

    insert_into(conn, 'people', {
        'firstname': 'John',
        'lastname': 'Doe',
        'age': 18, })
    

    Reference: https://github.com/PyMySQL/PyMySQL/blob/master/pymysql/cursors.py#L157-L158

    def execute(self, query, args=None):

    If args is a list or tuple, %s can be used as a placeholder in the query.
    If args is a dict, %(name)s can be used as a placeholder in the query.
    
    0 讨论(0)
提交回复
热议问题