Python MySQL-选择工作而不是删除?

2024-06-02 08:38:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python和Python的MySQL适配器的新手。我不确定我是否遗漏了一些显而易见的东西:

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))

有什么想法吗?


Tags: fromexecutedbconnectmysqlusernamedetailswhere
3条回答

可能您违反了外键约束。

你上面的代码, 只需添加对self.db.commit()的调用。

这一功能远不是什么烦恼:

它可以避免数据损坏问题 当查询中有错误时。

我猜您使用的是一个支持事务的存储引擎(例如InnoDB),但在删除之后不会调用db.commit()。如果不提交,删除的效果将被丢弃。

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.

另请参见这个类似的SO问题:Python MySQLdb update query fails

相关问题 更多 >