下面以兩個銀行賬戶之間的轉賬為例子進行演示。
要使用mysql中的事務處理,首先需要創建使用事務表類型(如bdb = berkeley db或innodb)的表。
create table account (
account_id bigint unsigned not null primary key auto_increment,
balance double
) type = innodb;
要在事務表上使用事務處理,必須要首先關閉自動提交:
set autocommit = 0;
事務處理以begin命令開始:
begin;
現在mysql客戶處在于服務器相關的事物上下文中。任何對事務表所做的改變在提交之前不會成為永久性的改變。
update account set balance = 50.25 where account_id = 1;
update account set balance = 100.25 where account_id = 2;
在做出所有的改變之后,使用commit命令完成事務處理:
commit;
當然,事務處理的真正優點是在執行第二條語句發生錯誤時體現出來的,若在提交前終止整個事務,可以進行回滾操作:
rollback;
下面是另一個例子,通過mysql直接進行數學運算:
select @first := balance from account where account_id = 1;
select @second := balance from account where account_id = 2;
update account set balance = @first - 25.00 where account_id = 1;
update account set balance = @second + 25.00 where account_id = 2;
除了commit命令外,下列命令也會自動結束當前事務:
alter table
begin
create index
drop database
drop table
lock tables
rename table
truncate
unlock tables
新聞熱點
疑難解答