標籤:
1.事務:一個或一系列的查詢;
2.使用事務安全的表格類型(通過InnoDB):
①關閉自動認可: set autocommit=0;
//若自動認可被開啟,須使用如下語句開始一個事務:
// start transaction; 若自動認可是關閉的則不需要此句
②完成組成事務的語句輸入後,提交給資料庫: commit;
③回到資料庫之前的狀態: rollback;
④將表格轉換成InnoDB表格(之前是MyISAM表格):
alter table orders type=innodb;
alter table order_items type=innodb;
//轉成InnoDB表格後,需要再使用commit;語句才能完成提交到資料庫的行為
3.(InnoDB下)添加外鍵:
要先建立一個使用外鍵的表格:
如:create table order_items{
……
}type=InnoDB;
再使用ALTER TABLE語句添加外鍵:
如: alter table order_items type=InnoDB;
alter table order_items
add foreign key (orderid) references orders(orderid);
//orderid列是一個外鍵,包含orders表格中的orderid列值
4.儲存:
①聲明一個預存程序:
# basic_stored_procedure.sql# Basic stored procedure exampledelimiter //# 分隔字元//替換; 使得在預存程序中使用分號分隔字元create procedure total_orders (out total float)# total_orders是預存程序名稱# out表示該參數將被傳出或返回(對應的是in)# total是被傳遞的參數,若有多個參數則用逗號分隔# float是參數的類型BEGIN select sum(amount) into total from orders;END//delimiter;# 過程聲明完成,將分隔字元重新設定為分號
過程聲明結束後,使用call關鍵字:
如: call total_orders(@t);
//調用total_orders過程並傳入一個用來儲存結果的變數@t
//查看結果: select @t;
②聲明一個儲存函數:
# basic_function.sql# Basic syntax to create a functiondelimiter //create function add_tax (price float) returns floatbegin declare tax float default 0.10; # declare用於在begin...end中聲明局部變數 return price*(1+tax);end//delimiter;
查看結果: select add_tax(100); //100是傳過去的price值
③查看定義預存程序和儲存函數:
show create procedure total_orders;
show create function add_tax;
刪除之:
drop procedure total_orders;
drop function add_tax;
④遊標、控制結構:
# control_structures_cursors.sql# Procedure to find the orderid with the largest amount# could be done with max, but just to illustrate stored procedure principlesdelimiter //create procedure largest_order(out largest_id int)begin declare this_id int; #當前行的orderid值 declare this_amount float; #當前行的amount值 declare l_amount float default 0.0; #最大的訂單金額 declare l_id int; #最大訂單金額對應的ID declare done int default 0; #迴圈標記 # 聲明控制代碼,類似於預存程序中的一個異常 #(該控制代碼將在sqlstate ‘02000‘語句被執行時調用) declare continue handler for sqlstate ‘02000‘ set done =1; # 遊標c1,類似於一個數組從一個查詢獲得結果集 declare c1 cursor for select orderid, amount from orders; open c1; #open才是真正開始執行查詢 repeat fetch c1 into this_id, this_amount; if not done then if this_amount>l_amount then set l_amount=this_amount; set l_id=this_id; end if; end if; until done end repeat; close c1; set largest_id=l_id;end//delimiter;
調用過程: call largest_order(@l);
查看結果: select @l;
第13章 MySQL進階編程