標籤:
1,前序
由於要重構APP(社交類) 服務端介面的部分代碼,故接觸到了 innoDB,以及事務這個詞,下面主要是以例子的形式顯示它的用法,理論的東西不過多講述。
2,何為事務
鄙人在編程方面的解釋:多條命令操作放在一起處理 , 例如提交的時候一起提交,撤銷的時候也是一起撤銷,書本對這個詞的定義內容很多。
3,myisam 與 innoDB
它們都是 mysql資料庫的引擎,我們一般建表預設的是 myisam 引擎,比較:http://www.cnblogs.com/vicenteforever/articles/1613119.html,個人認為,類 似於insert、update、delete 這種操作如果涉及多表或單表互聯操作的情況,為了避免資料寫髒,請使用事務。因為整個過程中若一條錯誤,便可以復原到開始時的狀態。
4,分享個基於php的類
1 <?php 2 3 /** 4 * Created by PhpStorm. 5 * User: 林冠宏 6 * Date: 2016/4/28 7 * Time: 10:20 8 */ 9 include "Config.php"; /** 資料庫配置資訊類,自行完善 */10 11 class Sql{12 public $link = null;13 private $config = null;14 /**15 * 是否直接開啟事務16 */17 public function Sql($begin = false){18 $this->config = new Config();19 $this->connect();20 mysql_query("SET AUTOCOMMIT=0",$this->link); /** 設定不自動認可,預設是自動認可 */21 if($begin){22 $this->SWBegin();23 }24 }25 26 public function connect(){27 $this->link = mysql_connect($this->config->host,$this->config->user,$this->config->pw); /** 串連資料庫 */28 mysql_query("SET NAMES ‘utf8‘",$this->link); /** 經驗總結,使用mysql設定頁面編碼,最好等連結了,再設定,意思是在連庫函數後面使用 */29 30 if(!$this->link){31 exit("connect_dataBase_wrong");32 }33 if(!mysql_select_db($this->config->db,$this->link)){34 exit("select_db_wrong");35 }36 }37 38 /**39 * 命令、是否判斷行數、出錯是否自動啟用復原、鏈式提交40 */41 public function exec($query,$judgeLength=false,$rollBack = false,$isCommit=false){42 $res = mysql_query($query,$this->link);43 if($judgeLength){ /** 是否判斷行數 */44 if(mysql_num_rows($res)<=0){45 return null;46 }47 }else{48 if(!$res){49 if($rollBack) {50 $this->rollBack();51 }52 exit($query); /** 拋出出錯的 sql 語句 */53 }54 }55 if($isCommit){56 return $this;57 }else{58 return $res;59 }60 }61 62 /** 開始事務 */63 public function SWBegin(){64 mysql_query("BEGIN",$this->link);65 }66 67 /** 復原 */68 public function rollBack(){69 mysql_query("ROLLBACK",$this->link);70 }71 72 /** 提交事務 */73 public function commit($getThis=false){74 mysql_query("COMMIT",$this->link);75 if($getThis){76 return $this;77 }else{78 return null;79 }80 }81 }82 83 ?>
5,例子
1 <?php 2 /** 3 * Created by PhpStorm. 4 * User: 林冠宏 5 * Date: 2015/10/24 6 * Time: 11:23 7 */ 8 9 include "Sql.php";10 $sql = new Sql();11 12 /** 往 aa 表中插入一批資料,注意建aa表的時候要選擇 innoDB 引擎 */13 for($i=0;$i<10;$i++){14 $temp = $i."k";15 $query = "insert into aa (a,w) values(‘$i‘,‘$temp‘)";16 $sql->exec($query);17 }18 19 /** 下面的注釋君請自行開啟看效果 */20 //$sql->rollBack(); /** 復原的話,上面的所有insert不會被執行 */21 //$sql->commit(); /** 不commit提交的話,上面的insert也不會被執行 */22 23 /** select 操作不用commit也可以直接使用 結果集 */24 /*25 $result = $sql->exec("select * from aa");26 while($row = mysql_fetch_assoc($result)){27 print($row)."</br>";28 }29 */30 31 ?>
MySql - InnoDB - 事務 , Php版