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

前端 未结 3 930
说谎
说谎 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: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.
    

提交回复
热议问题