mysql.exe -h localhost -P 3306 -u root -p
use mydb;?????——???? 進入數據庫
查看:show index from 表名\G
desc:查看表結構
select * from 表名:查詢所有數據?
提交事務:commit; 同步數據表,表示操作成功
回滾事務:rollback; 直接清空日志表,表示操作失敗
事務transaction
事務的操作只針對數據操作,不針對表
涉及到安全方面的問題用事務—使用事務的前提存儲引擎必須是innodb
-- 創建一個賬戶
create table my_account(
id int primary key auto_increment,
number char(16) not null unique comment '賬戶',
name varchar(20) not null,
money decimal(10,2)default 0.0 comment '賬戶余額'
)charset utf8;
-- 插入數據
insert into my_account values
(null,'0000000000000001','張三',1000),
(null,'0000000000000002','李四',2000);
-- 張三轉賬1000元給李四
update my_account set money=money-1000 where id=1;
一、事務操作分兩種:自動事務(默認)、手動事務
1)手動事務的操作流程
? ? ? ? ? ? 1> 開啟事務:start transaction;
-- 事務安全
-- 開啟事務
start transaction;
? ? ? ? ? ? 2> 進行事務操作
-- 事務操作:1、李四賬戶減少
update my_account set money=money-1000 where id=2;
-- 事務操作:2、張三賬戶增加
update my_account set money=money+1000 where id=1;
? ? ? ? ? ? 3> 關閉事務
????????????????????????提交事務:commit; 同步數據表,表示操作成功
-- 提交事務
commit;
????????????????????????回滾事務:rollback; 直接清空日志表,表示操作失敗
-- 回滾事務:會清空
rollback;
二、事務操作原理:
事務開啟之后,所有的操作都會臨時保存到事務日志,而事務日志只有在得到commit命令才會同步到數據表,其他任何情況都會清空,比如rollback、斷電、斷開連接
三、回滾點
????????????1)設置回滾點語法:savepoint 回滾點名字;
????????????2)回到回滾點語法:rollback to 回滾點名字;
-- 設置回滾點
savepoint sp1;
-- 銀行扣稅
update my_account set money=money-10000*0.05 where id=2;-- 錯誤
-- 回滾到回滾點
rollback to sp1;
-- 繼續操作
update my_account set money=money-10000*0.05 where id=1;
-- 查看結果
select * from my_account;
-- 提交結果
commit;
-- 如果要注冊一個用戶 用戶名 》密碼 》驗證碼 —— 如果不注冊,將全回滾用rollback
-- 如果要注冊一個用戶 用戶名 》密碼 》驗證碼 —— 如果重新輸入驗證碼,將用回滾點rollback to
回滾喝回滾點的不同
rollback :所有操作都不要了
rollback to:回到某個回滾點之后的錯誤操作目標
四、自動事務處理
? ? ? ? ? ? 1)show variables like 'autocommit';
? ? ? ? ? ? 2)關閉事務自動提交:set autocommit=off/0;
關閉自動提交后,增、刪、改就只能手動提交(commit)
打開事務自動提交:set autocommit=off/;——默認
-- 顯示系統變量autocommit(模糊查詢)
show variables like 'autocommit';
-- 關閉事務自動提交
set autocommit=0;
update my_account set money=money+10000 where id=2;
commit;
-- 打開事務自動提交
set autocommit=1;
update my_account set money=money-10000*0.05 where id=2;
五、(數據庫)事務的四大特性:ACID
????????????A:Atomic,原子性(要么都成功,要么都失敗)
????????????C:Consistency,一致性(只要開啟事務,沒有開啟commit,另一個窗口沒有影響)
????????????I:Isolation,隔離性(兩個窗口都在進行事務,互不影響)
????????????D:Durability,持久性(只要提交了,rollback也沒用)
-- 隔離性
start transaction;
-- 給張三返稅,反500元
update my_account set money=money+500 where id=1;
-- (在另一個命令行輸入)隔離性
start transaction;
-- (在另一個命令行輸入)李四淘寶花了500元
update my_account set money=money-500 where id=2;
-- 兩個命令行都可以查?
select * from my_account;?
rollback;?
select * from my_account;
六、鎖機制(有時候行鎖,有時候表鎖,有時候頁鎖)
-- 鎖機制
start transaction;
update my_account set money=money+500 where name='張三';-- 整體找,直到找到所有的‘張三’
-- (在另一個命令行輸入)李四+1000元
update my_account set money=money+1000 where id=2;
rollback;