简体   繁体   中英

How can I undo a mysql statement that I just executed?

如何撤消最近执行的mysql查询?

If you define table type as InnoDB, you can use transactions. You will need set AUTOCOMMIT=0 , and after you can issue COMMIT or ROLLBACK at the end of query or session to submit or cancel a transaction.

ROLLBACK -- will undo the changes that you have made

You can only do so during a transaction.

BEGIN;
INSERT INTO xxx ...;
DELETE FROM ...;

Then you can either:

COMMIT; -- will confirm your changes

Or

ROLLBACK -- will undo your previous changes

Basically: If you're doing a transaction just do a rollback. Otherwise, you can't "undo" a MySQL query.

对于某些指令,如ALTER TABLE,即使使用事务( 12 ),MySQL也无法做到这一点。

You can stop a query which is being processed by this

Find the Id of the query process by => show processlist;

Then => kill id;

in case you do not only need to undo your last query (although your question actually only points on that, I know) and therefore if a transaction might not help you out, you need to implement a workaround for this:

copy the original data before commiting your query and write it back on demand based on the unique id that must be the same in both tables; your rollback-table (with the copies of the unchanged data) and your actual table (containing the data that should be "undone" than). for databases having many tables, one single "rollback-table" containing structured dumps/copies of the original data would be better to use then one for each actual table. it would contain the name of the actual table, the unique id of the row, and in a third field the content in any desired format that represents the data structure and values clearly (eg XML). based on the first two fields this third one would be parsed and written back to the actual table. a fourth field with a timestamp would help cleaning up this rollback-table.

since there is no real undo in SQL-dialects despite "rollback" in a transaction (please correct me if I'm wrong - maybe there now is one), this is the only way, I guess, and you have to write the code for it on your own.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM