在MySQL中使用触发器Trigger的操作过程

WBOY
풀어 주다: 2016-06-07 16:39:46
원래의
1274명이 탐색했습니다.

想监控Bugzilla数据库中几个重要的表,如果它们发生了任何改变(增、删、改),都希望能够记录下来,以便后面再写程序来分析。很自然,就想到使用MySQL的触发器(Trigger)了,学习了一会,记录如下: 1. 先建立一个新的表用于记录我需要的变化: CREATE TAB

想监控Bugzilla数据库中几个重要的表,如果它们发生了任何改变(增、删、改),都希望能够记录下来,以便后面再写程序来分析。很自然,就想到使用MySQL的触发器(Trigger)了,学习了一会,记录如下:
1. 先建立一个新的表用于记录我需要的变化:

CREATE TABLE `bugzilla_log` (
  `id` INT UNSIGNED NOT NULL,
  `table` varchar(80) NOT NULL,
  `action` ENUM('insert','update','delete'),
  `ts` TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='logging some important changes in bugzilla DB';
로그인 후 복사


2. 针对需要监控的表,创建触发器:

CREATE
    TRIGGER `classifications_insert`
    AFTER INSERT
    ON classifications FOR EACH ROW
    INSERT INTO `bugzilla_log` (`id`, `table`, `action`, `ts`) VALUES (NEW.id, 'classifications', 'insert', NOW()); 
?
CREATE
    TRIGGER `classifications_update`
    AFTER UPDATE
    ON classifications FOR EACH ROW
    INSERT INTO `bugzilla_log` (`id`, `table`, `action`, `ts`) VALUES (NEW.id, 'classifications', 'update', NOW()); 
?
CREATE
    TRIGGER `classifications_delete`
    BEFORE DELETE
    ON classifications FOR EACH ROW
    INSERT INTO `bugzilla_log` (`id`, `table`, `action`, `ts`) VALUES (OLD.id, 'classifications', 'delete', NOW());
로그인 후 복사

请注意其中AFTER和BEFORE,以及OLD和NEW的使用。
Within the trigger body, you can refer to columns in the subject table (the table associated with the trigger) by using the aliases OLD and NEW. OLD.col_name refers to a column of an existing row before it is updated or deleted. NEW.col_name refers to the column of a new row to be inserted or an existing row after it is updated.

3. 查看当前数据库中的触发器:

SHOW TRIGGERS;
로그인 후 복사

参考资料:

http://dev.mysql.com/doc/refman/5.5/en/create-trigger.html

http://www.jicdesign.com/blog/web-development/how-to-use-mysql-triggers-to-log-table-changes.html

Original article: 在MySQL中使用触发器Trigger的操作过程

©2014 笑遍世界. All Rights Reserved.

원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!