Home | 简体中文 | 繁体中文 | 杂文 | 知乎专栏 | 视频教程 | bilibili | Github | OSChina 博客 | 云社区 | 云栖社区 | Facebook | Linkedin | 打赏(Donations) | About
知乎专栏多维度架构 | 微信号 netkiller-ebook | 51CTO:视频教程

22.3. 保护表字段

通过触发器,使之无法修改某些字段的数据,同时不影响修改其他字段。

		
DROP TRIGGER IF EXISTS `members`;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='';
DELIMITER //
CREATE TRIGGER `members` BEFORE UPDATE ON `members` FOR EACH ROW BEGIN
	set new.name = old.name;
	set new.cellphone = old.cellphone;
	set new.email = old.email;
	set new.password = old.password;
END//
DELIMITER ;
SET SQL_MODE=@OLD_SQL_MODE;
		
		

再举一个例子

		
CREATE TABLE `account` (
	`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
	`user` VARCHAR(50) NOT NULL DEFAULT '0',
	`cash` FLOAT NOT NULL DEFAULT '0',
	PRIMARY KEY (`id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB;
		
		

每一次数据变化新增一条数据

		
INSERT INTO `test`.`account` (`user`, `cash`) VALUES ('neo', -10);
INSERT INTO `test`.`account` (`user`, `cash`) VALUES ('neo', -5);
INSERT INTO `test`.`account` (`user`, `cash`) VALUES ('neo', 30);
INSERT INTO `test`.`account` (`user`, `cash`) VALUES ('neo', -20);
		
		

保护用户的余额不被修改

		
DROP TRIGGER IF EXISTS `account`;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='';
DELIMITER //
CREATE TRIGGER `account` BEFORE UPDATE ON `account` FOR EACH ROW BEGIN
	set new.cash = old.cash;
END//
DELIMITER ;
SET SQL_MODE=@OLD_SQL_MODE;
		
		
网站:http://www.netkiller.cn/ | 知乎:netkiller | 51CTO:视频教程 | Bilibili:netkiller | Github:netkiller