注意支持事务的表必须是InnoDB类型。本例在 PHP5.2.5+MySQL5.0下测试通过。open_article 表的结构为:
- SET FOREIGN_KEY_CHECKS=0;
- — —————————-
- — Table structure for open_article
- — —————————-
- CREATE TABLE `open_article` (
- `nId` int(11) NOT NULL auto_increment,
- `nOrder` int(11) default ‘0′,
- `sTopic` varchar(100) default NULL,
- `sContent` varchar(255) default NULL,
- `dDatetime` timestamp NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
- PRIMARY KEY (`nId`)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
- <?PHP
- header(”Content-Type:text/html;charset=utf-8″);
- $host = “localhost”;
- $user = “root”;
- $password = “mypassword”;
- $db = “test_store_proc”;
- $dblink = mysql_connect($host, $user, $password) or die(”Can’t connect to mysql”);
- mysql_select_db($db, $dblink);
- mysql_query(”SET NAMES UTF8″);
- /* 创建事务 */
- mysql_query(’START TRANSACTION’) or exit(mysql_error());
- //第1条插入语句:
- $sql = “insert into open_article (nOrder, sTopic, sContent) values (0, ‘News Main Topic-1′,’资讯内容-1′)”;
- if(!mysql_query($sql))
- {
- echo $sql .’:<br>’. mysql_errno() . “:” . mysql_error() . “<br>”;
- mysql_query(’ROLLBACK’) or exit(’ROLLBACKing:’. mysql_error()); //判断当执行失败时回滚
- exit;
- }
- //第2条插入语句:
- $sql = “insert into open_article (nOrder, sTopic, sContent) values (0, ‘News Main Topic-2′,’资讯内容-2′)”;
- if(!mysql_query($sql))
- {
- echo $sql .’:<br>’. mysql_errno() . “:” . mysql_error() . “<br>”;
- mysql_query(’ROLLBACK’) or exit(’ROLLBACKing:’. mysql_error()); //判断当执行失败时回滚
- exit;
- }
- mysql_query(’COMMIT’) or exit(mysql_error()); //执行事务
- mysql_close($dblink);
- ?>
如果把第2条插入SQL语句改为:
$sql = “insert into open_article (nOrder, sTopic2, sContent) values (0, ‘News Main Topic-2′,’资讯内容-2′)”;
由于sTopic2字段不存在,程序会报错终止。这时会发现没有记录被插入到表中,说明第1条插入SQL语句也没有生效,实际是被事务回滚了。
怎么看出是“被事务回滚了”?因为open_article表的有个自动增量字段 nId。当重新纠正第2条插入SQL语句,再运行程序时,会发现 nId 的值跳了1,说明前次第1条插入SQL语句确实被执行了,然后又被取消了。
结果记录:
— —————————-
— Records
— —————————-
INSERT INTO `open_article` VALUES (’1′, ‘0′, ‘News Main Topic-1′, ‘资讯内容-1′, ‘2010-03-06 05:59:07′);
INSERT INTO `open_article` VALUES (’2′, ‘0′, ‘News Main Topic-2′, ‘资讯内容-2′, ‘2010-03-06 05:59:07′);
INSERT INTO `open_article` VALUES (’3′, ‘0′, ‘News Main Topic-1′, ‘资讯内容-1′, ‘2010-03-06 06:00:13′);
INSERT INTO `open_article` VALUES (’4′, ‘0′, ‘News Main Topic-2′, ‘资讯内容-2′, ‘2010-03-06 06:00:13′);
INSERT INTO `open_article` VALUES (’6′, ‘0′, ‘News Main Topic-1′, ‘资讯内容-1′, ‘2010-03-06 06:06:13′);
INSERT INTO `open_article` VALUES (’7′, ‘0′, ‘News Main Topic-2′, ‘资讯内容-2′, ‘2010-03-06 06:06:13′);
INSERT INTO `open_article` VALUES (’8′, ‘0′, ‘News Main Topic-1′, ‘资讯内容-1′, ‘2010-03-06 06:11:46′);
INSERT INTO `open_article` VALUES (’9′, ‘0′, ‘News Main Topic-2′, ‘资讯内容-2′, ‘2010-03-06 06:11:46′);
注意上列记录中,缺少 nId = 5 的记录。
测试代码需要保存成 utf8 格式。