系統觸發器用於監視數據庫服務的打開、關閉、錯誤等信息的取得,或者是監控用戶的行為操作等。如果要創建系統觸發器,可以使用如下的語法
CREATE [OR REPLACE] TRIGGER 觸發器名稱 [BEFORE | AFTER] [數據庫事件] ON [DATABASE | SCHEMA] [WHEN 觸發條件] [DECLARE] [程序聲明部分 ;] BEGIN 程序代碼部分 ; END [觸發器名稱] ;
示例一、登錄登出日志功能
--創建序列 CREATE SEQUENCE user_log_seq; --創建日志表 CREATE TABLE user_log( logid NUMBER CONSTRAINT pk_logoid PRIMARY KEY, username VARCHAR2(50) NOT NULL, logodate DATE, logoffdate DATE, ip VARCHAR2(20), logtype VARCHAR2(20) );
--創建登錄觸發器 create or replace trigger logon_trigger AFTER LOGON ON DATABASE declare begin INSERT INTO user_log(logid,username,logodate,ip,logtype) VALUES(user_log_seq.nextval,ora_login_user,SYSDATE,ora_client_ip_address,'LOGON'); end logon_trigger;
--創建登出觸發器 CREATE OR REPLACE TRIGGER LOGON_TRIGGER BEFORE LOGOFF ON DATABASE DECLARE BEGIN INSERT INTO USER_LOG (LOGID, USERNAME, LOGOFFDATE, IP, LOGTYPE) VALUES (USER_LOG_SEQ.NEXTVAL, ORA_LOGIN_USER, SYSDATE, ORA_CLIENT_IP_ADDRESS, 'LOGFF'); END LOGON_TRIGGER;
切換用戶進行登錄
使用管理登錄,查看user_log表
SELECT * FROM user_log;
示例二、 系統啟動和關閉時,日志記錄功能
--創建索引 CREATE SEQUENCE db_event_log_seq; --查詢索引 SELECT * FROM user_sequences WHERE sequence_name='DB_EVENT_LOG_SEQ'; --創建數據庫記錄事件表 CREATE TABLE db_event_log( eventid NUMBER CONSTRAINT pk_eventid PRIMARY KEY, enentType VARCHAR2(50) NOT NULL, enentDate DATE NOT NULL, eventUser VARCHAR2(50) NOT NULL ); --查詢表 SELECT * FROM db_event_log;
--創建啟動之後觸發器 create or replace trigger startup_trigger after startup ON DATABASE declare BEGIN INSERT INTO db_event_log(eventid,enenttype,enentdate,eventuser) VALUES(db_event_log_seq.nextval,'STARTUP',SYSDATE,ora_login_user); COMMIT; end startup_trigger; --創建關閉之前觸發器 create or replace trigger shutdown_trigger before shutdown ON DATABASE declare begin INSERT INTO db_event_log(eventid,enenttype,enentdate,eventuser) VALUES(db_event_log_seq.nextval,'SHUTDOWN',SYSDATE,ora_login_user); COMMIT; end shutdown_trigger;
-測試在sqlplus中執行 SHUTDOWN ABORT; --立刻關閉 startup --啟動 SELECT * FROM db_event_log;
示例三、 錯誤信息日志
--創建索引 CREATE SEQUENCE db_error_seq; --查詢索引 SELECT * FROM user_sequences WHERE sequence_name='DB_ERROR_SEQ'; ---創建一張記錄錯誤信息的數據表 CREATE TABLE db_error( eid NUMBER CONSTRAINT pk_eid PRIMARY KEY, username VARCHAR2(50), errorDate DATE, dbname VARCHAR2(50), CONTENT CLOB ); --查詢表 SELECT * FROM db_error;
--創建數據庫錯誤觸發器 create or replace trigger error_trigger after servererror ON DATABASE declare begin INSERT INTO db_error(eid,username,errordate,dbname,content) VALUES(db_error_seq.nextval,ora_login_user,SYSDATE,ora_database_name,dbms_utility.format_error_stack); --ora_login_user 用戶名 --ora_database_name 數據庫名 --dbms_utility包 --dbms_utility.format_error_stack錯誤內容 end error_trigger;
--測試 --使用普通用戶 SELECT * FROM orcl; INSERT INTO dept(deptno,dname,loc) VALUES(10,'111','SZ'); --查詢表 SELECT * FROM db_error;