mysql数据库事务,没想到也不是很难

<?php 
mysql_connect('localhost','root','');
mysql_select_db('test');
mysql_query ( "SET AUTOCOMMIT=0" ); //設置mysql不自動提交,需自行用commit語句提交
$sql 	= "INSERT INTO  `test`.`testTable` (`id` ,`a` ,`b` ,`wTime`)VALUES (NULL ,  '10',  '20', NOW( ))";
$sql1 	= "INSERT INTO  `test`.`testTable` (`id` ,`a` ,`b` ,`wTime`)VALUES (NULL ,  '101',  '201', NOW( ))";
$res 	= mysql_query ( $sql );
$res1 	= mysql_query ( $sql1 );
//因爲使用了事務,則兩個insert都執行失敗
if ($res && $res1) {
	mysql_query ( "COMMIT" );
} else {
	mysql_query ( "ROLLBACK" );
}
 
mysql_query ( "SET AUTOCOMMIT=1" );//設置mysql自動提交
$sql3	=	"INSERT INTO  `test`.`testTable` (`id` ,`a` ,`b` ,`wTime`)VALUES (NULL ,  '100',  '200', NOW( ))";
mysql_query ( $sql3 );
 
/*
 * 创建数据库文件,注意一定要是INNODB
CREATE TABLE  `test`.`testTable` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`a` VARCHAR( 50 ) NOT NULL ,
`b` VARCHAR( 50 ) NOT NULL ,
`wTime` DATETIME NOT NULL
) ENGINE = INNODB;
*/
?>

参考:
http://www.cnblogs.com/fightLonely/archive/2011/06/09/2076092.html
http://koda.iteye.com/blog/471713

Related posts:

Leave a Reply

Your email address will not be published.