案例一:当表sys_user新增、修改、删除时后,触发触发器记录操作状态。
第一步:创建更新记录表
create table user_update_log
(
id number(5) not null,
username varchar(10),
operation varchar(6),
operatetime date,
primary key(id)
);
第二步:创建一个序列,在SQLplus控制台执行如下脚本
create sequence logsequence start with 1 maxvalue 999;
第三步:创建一个触发器,在SQLplus控制台执行如下脚本
create or replace trigger user_trigger
after insert or update or delete on sys_user
for each row
declare
-- local variables here
operation user_update_log.operation%TYPE;
begin
if inserting then
operation := 'insert';
elsif updating then
operation := 'update';
elsif deleting then
operation := 'delete';
else
operation := 'unknown';
end if;
-- dbms_output.put_line(operation);
--:old.state获取就数据;new.state获取新数据;
dbms_output.put_line(operation||'old='||:old.state||' new='||:new.state);
insert into user_update_log values (logsequence.nextval, user, operation, sysdate);
dbms_output.put_line('success');
end user_trigger;
第四步:测试
update sys_user a set a.state=0 where user_id=248;
update sys_user a set a.state=0 where user_id=258;
测试结果为:
updateold=0 new=1
success
updateold=0 new=1
success
案例二、当表sys_org_info新增、修改、删除时后,更新sys_user数据,函数调用java方法
第一步:在PL/SQL创建java类,更新用户表某记录值
create or replace and compile java source named orcjavademo as
import java.sql.*;
import oracle.jdbc.*;
public class OrcJavaDemo
{
public static String entry(String hell)
{
System.out.println(hell);
optOrc(hell);
return hell+"=ok";
}
/*数据库操作*/
public static void optOrc(String hell){
try {
String driver = "oracle.jdbc.driver.OracleDriver";
String strUrl = "jdbc:oracle:thin:@172.20.0.95:1521:ilmsddd";
Connection conn =DriverManager.getConnection("jdbc:default:connection:");
//Class.forName(driver);
//conn = DriverManager.getConnection(strUrl, "atmsd", "atmsd");
//String sql ="update sys_org_info set org_min_name=? where org_cd='001001' ";
String sql="update sys_user set state=? where user_id=258";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1,3);
pstmt.executeUpdate();
pstmt.close();
}
catch(SQLException e) {
System.err.println("ERROR! Adding Salgrade: "
+ e.getMessage());
}
}
}
第二步:创建函数
CREATE OR REPLACE FUNCTION testFun(file in varchar2) return varchar2
AS LANGUAGE JAVA NAME 'OrcJavaDemo.entry(java.lang.String) return java.lang.String';
第三步:创建触发器
create or replace trigger sys_user_trigger
after insert or update or delete on sys_org_info
for each row
declare
-- local variables here
operation sys_org_info.org_name%type;
opt1 varchar2(50);
-- operation user_update_log.operation%TYPE;
begin
if inserting then
operation := 'insert';
elsif updating then
operation := 'update';
opt1:='update';
elsif deleting then
operation := 'delete';
else
operation := 'unknown';
end if;
dbms_output.put_line(operation);
dbms_output.put_line('success');
--optMethod(operation);
dbms_output.put_line(testFun(opt1));
end sys_user_trigger;
第四步:测试
update sys_org_info set org_name='a' where org_cd='001001';
输出结果为
update
success
updateold=2 new=3
success
update=ok