MySQL 如何建立事務

2021-10-24 07:45:11 字數 1605 閱讀 7008

#事務的建立

/*隱式的事務:事務沒有明顯的開啟和結束的標記

比如insert、update、delete語句

delete from 表 where id=1;

顯示事務:事物具有明顯的開啟和結束的標記

前提:必須先設定自動提交功能為禁用

set autocommit=0;

步驟1:開啟事務

set autocommit=0;

start transaction;可選的

步驟2:編寫事務中的sql語句(select、insert、update、delete)

語句1;

語句2;

......

步驟3:結束事務

commit;提交事務

rollback;回滾事務

開啟事務的語句

update 表 set 張三丰的餘額=500 where name='張三丰';

update 表 set 郭襄的餘額=1500 where name='郭襄';

結束事務的語句;

*/show variables like

'autocommit'

;drop

table

ifexists account;

create

table account(

id int

primary

keyauto_increment

, username varchar(20

),balance double);

insert

into account(username,balance)

values

('張無忌'

,1000),

('趙敏'

,1000);

#演示事務的使用步驟

#開啟事務

set autocommit=0;

start

transaction

;#編寫一組事務的語句

update account set balance=

500where username=

'張無忌'

;update account set balance=

1500

where username=

'趙敏'

;#結束事務

commit

;select

*from account;

#試一下回滾的

#開啟事務

set autocommit=0;

start

transaction

;#編寫一組事務的語句

update account set balance=

1000

where username=

'張無忌'

;update account set balance=

1000

where username=

'趙敏'

;#結束事務

rollback

;#在沒有明確的結束標誌,只是滯留在記憶體了。

回滾:可以返回上次的回滾點。

建立mysql事務 資料庫事務的建立

使用事務解決銀行轉賬問題 關鍵語句講解 begin transaction 定義變數,用於累計事務執行過程中的錯誤 declare errorsum int set errorsum 0 初始化為0,即無錯誤 轉賬 張三的賬戶少1000元,李四的賬戶多1000元 update bank set cu...

mysql如何建立外檢 mysql如何建立外來鍵

乙個主表blog部落格表,drop table if exists blog create table blog id int 11 not null auto increment,title varchar 11 default null,content varchar 11 default nu...

mysql表如何建立 如何建立mysql表?

mysql中建立資料表的語法為 create table table name column name column type 在mysql 提示符下,建立乙個mysql表這是很容易的。使用 sql 命令 create table 來建立表。在建立表前需要使用use databasename命令選擇...