【问题标题】:python mysql delete statement not workingpython mysql删除语句不起作用
【发布时间】:2012-08-22 22:38:37
【问题描述】:

在这里,我正在尝试删除电子邮件/用户名中包含“”的所有用户。

    def removeQuote(self, tbl,record):
            """ Updates the record """
            statmt="select id from %s WHERE `email` LIKE '%%\"%%'" % (tbl)
            self.cursor.execute(statmt)
            rows=list(self.cursor.fetchall())
            for idx, val in enumerate(rows):
                    id= val[0]
                    delstatmt = "DELETE FROM `maillist_subscription` WHERE id = '%s'" % id
                    print delstatmt
                    self.cursor.execute(delstatmt)

此操作的输出显示好像操作已成功完成,但记录仍保留在数据库中。 输出还显示了正确的 mysql 语句:

DELETE FROM `maillist_subscription` WHERE id = '8288754'

感谢您的帮助!

【问题讨论】:

    标签: python sql transactional


    【解决方案1】:

    您需要使用连接对象上的 commit() 方法提交更改。大多数 DBAPI 接口使用隐式事务。

    另外,不要在 SQL 查询生成中使用字符串格式!它会让你接触到 SQL 注入:

    不安全!!

    # What happens if id = "1'; DROP DATABASE somedb" ?
    delstatmt = "DELETE FROM `maillist_subscription` WHERE id = '%s'" % (id,)
    cursor.execute(delstatmt)
    conn.commit()
    

    安全!

    delstatmt = "DELETE FROM `maillist_subscription` WHERE id = ?"
    cursor.execute(delstatmt, (id,))
    conn.commit()
    

    【讨论】:

    • 如果有人尝试注入查询,如果在不安全的方法中不使用multi=True 调用execute,客户端不会失败吗?
    • @user666412 始终以正确的方式进行操作,您不会允许任何人使用您的查询逻辑。考虑上面的不安全方法,其中id为123' OR TRUE--
    【解决方案2】:

    cursor.execute("DELETE FROM maillist_subscription WHERE id = '"+id+"'")

    conn.commit()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-31
      • 1970-01-01
      • 2018-09-25
      • 2017-01-17
      • 1970-01-01
      • 1970-01-01
      • 2013-04-02
      • 1970-01-01
      相关资源
      最近更新 更多