Python MySQL - SELECTs work but not DELETEs?

强颜欢笑 提交于 2019-12-01 14:57:24

问题


I'm new to Python and Python's MySQL adapter. I'm not sure if I'm missing something obvious here:

db = MySQLdb.connect(# db details omitted)
cursor = self.db.cursor()

# WORKS
cursor.execute("SELECT site_id FROM users WHERE username=%s", (username))
record = cursor.fetchone()

# DOES NOT SEEM TO WORK
cursor.execute("DELETE FROM users WHERE username=%s", (username))

Any ideas?


回答1:


I'd guess that you are using a storage engine that supports transactions (e.g. InnoDB) but you don't call db.commit() after the DELETE. The effect of the DELETE is discarded if you don't commit.

See http://mysql-python.sourceforge.net/FAQ.html#my-data-disappeared-or-won-t-go-away:

Starting with 1.2.0, MySQLdb disables autocommit by default, as required by the DB-API standard (PEP-249). If you are using InnoDB tables or some other type of transactional table type, you'll need to do connection.commit() before closing the connection, or else none of your changes will be written to the database.

See also this similar SO question: Python MySQLdb update query fails




回答2:


Perhaps you are violating a foreign key constraint.




回答3:


To your code above, just add a call to self.db.commit().

The feature is far from an annoyance:

It saves you from data corruption issues when there are errors in your queries.




回答4:


The problem might be that you are not committing the changes. it can be done by conn.commit()

read more on this here



来源:https://stackoverflow.com/questions/1451782/python-mysql-selects-work-but-not-deletes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!