MySQL数据库安全之防止撰改的方法

网络编程 2021-07-05 15:27www.168986.cn编程入门
这篇文章主要介绍了MySQL数据库防止撰改的方法,需要的朋友可以参考下

MySQL数据库可以通过触发器,使之无法修改某些字段的数据,又不会影响修改其他字段。

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 `aount` (
 `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`.`aount` (`user`, `cash`) VALUES ('neo', -10);
INSERT INTO `test`.`aount` (`user`, `cash`) VALUES ('neo', -5);
INSERT INTO `test`.`aount` (`user`, `cash`) VALUES ('neo', 30);
INSERT INTO `test`.`aount` (`user`, `cash`) VALUES ('neo', -20);

保护用户的余额不被修改

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

Copyright © 2016-2025 www.168986.cn 狼蚁网络 版权所有 Power by