使用java監控oracle數據庫的變化,主要是針對表數據,若是發生變化,使用select去查詢,可以達到推送的目的java
1 package com.test.notifi; 2 3 import java.sql.ResultSet; 4 import java.sql.SQLException; 5 import java.sql.Statement; 6 import java.util.Properties; 7 import oracle.jdbc.OracleConnection; 8 import oracle.jdbc.OracleDriver; 9 import oracle.jdbc.OracleStatement; 10 import oracle.jdbc.dcn.DatabaseChangeEvent; 11 import oracle.jdbc.dcn.DatabaseChangeListener; 12 import oracle.jdbc.dcn.DatabaseChangeRegistration; 13 import oracle.jdbc.pool.OracleDataSource; 14 15 public class TestNotification { 16 17 public void run(){ 18 OracleDataSource dataSource; 19 try { 20 dataSource = new OracleDataSource(); 21 dataSource.setUser("hw"); 22 dataSource.setPassword("112311"); 23 dataSource.setURL("jdbc:oracle:thin:@198.22.1.4:1521:COPYDB1"); 24 OracleConnection conn = (OracleConnection) dataSource.getConnection(); 25 26 Properties prop = new Properties(); 27 prop.setProperty(OracleConnection.DCN_NOTIFY_ROWIDS,"true"); 28 prop.setProperty(OracleConnection.DCN_QUERY_CHANGE_NOTIFICATION,"true"); 29 DatabaseChangeRegistration dcr = conn.registerDatabaseChangeNotification(prop); 30 31 DCNDemoListener list = new DCNDemoListener(this); 32 dcr.addListener(list); 33 34 Statement stmt = conn.createStatement(); 35 36 ((OracleStatement)stmt).setDatabaseChangeRegistration(dcr); 37 // ResultSet rs = stmt.executeQuery("select * from hs_secu.entrust a where a.fund_account = '610005385'"); 38 ResultSet rs = stmt.executeQuery("select * from stocc"); 39 while (rs.next()) 40 {} 41 String[] tableNames = dcr.getTables(); 42 for(int i=0;i<tableNames.length;i++) 43 System.out.println(tableNames[i]+" is part of the registration."); 44 rs.close(); 45 stmt.close(); 46 conn.close(); 47 } catch (SQLException e) { 48 // TODO Auto-generated catch block 49 e.printStackTrace(); 50 51 } 52 } 53 54 public static void main(String[] a) { 55 TestNotification notification = new TestNotification(); 56 notification.run(); 57 } 58 59 }
1 package com.test.notifi; 2 3 import oracle.jdbc.dcn.DatabaseChangeEvent; 4 import oracle.jdbc.dcn.DatabaseChangeListener; 5 6 class DCNDemoListener implements DatabaseChangeListener 7 { 8 TestNotification demo; 9 DCNDemoListener(TestNotification dem) 10 { 11 demo = dem; 12 } 13 public void onDatabaseChangeNotification(DatabaseChangeEvent e) 14 { 15 Thread t = Thread.currentThread(); 16 System.out.println("DCNDemoListener: got an event ("+this+" running on thread "+t+")"); 17 System.out.println(e.toString()); 18 synchronized( demo ){ demo.notify();} 19 } 20 }
使用windows機器去運行這個程序的時候,請注意,hostname須要添加本身的IP和主機名稱sql
例如: 198.28.1.2 TIM-PC數據庫
這樣oracle數據庫才能知道是誰註冊的windows