java调用ORACLE CDC 监控数据变化Code:

package oracleCDC;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import oracle.jdbc.OracleConnection;
import oracle.jdbc.OracleDriver;
import oracle.jdbc.OracleStatement;
import oracle.jdbc.dcn.DatabaseChangeEvent;
import oracle.jdbc.dcn.DatabaseChangeListener;
import oracle.jdbc.dcn.DatabaseChangeRegistration;
 
public class DBChangeNotification
{
  static final String USERNAME= "system";
  static final String PASSWORD= "manager";
  static String URL="jdbc:oracle:thin:@//192.168.12.128:1521/orcl";
  
  public static void main(String[] argv)
  {
   
  
    DBChangeNotification demo = new DBChangeNotification();
    try
    {
      demo.run();
    }
    catch(SQLException mainSQLException )
    {
      mainSQLException.printStackTrace();
    }
  }
 
  void run() throws SQLException
  {
    OracleConnection conn = connect();
      
    Properties prop = new Properties();
    
    prop.setProperty(OracleConnection.DCN_NOTIFY_ROWIDS,"true");
    prop.setProperty(OracleConnection.DCN_QUERY_CHANGE_NOTIFICATION,"true");
 
    DatabaseChangeRegistration dcr = conn.registerDatabaseChangeNotification(prop);
 
    try
    {
      DCNDemoListener list = new DCNDemoListener(this);
      dcr.addListener(list);
       
      Statement stmt = conn.createStatement();
      ((OracleStatement)stmt).setDatabaseChangeRegistration(dcr);
      ResultSet rs = stmt.executeQuery("select * from SCOTT.dept where deptno='45'");
     
      while (rs.next())
      {}
      ResultSet rs1= stmt.executeQuery("select * from SCOTT.SALGRADE where GRADE='110'");

      while (rs1.next())
      {}
      String[] tableNames = dcr.getTables();
      for(int i=0;i<tableNames.length;i++)
        System.out.println(tableNames[i]+" is part of the registration.");
      rs.close();
    }
    catch(SQLException ex)
    {
      if(conn != null)
        conn.unregisterDatabaseChangeNotification(dcr);
      throw ex;
    }
    finally
    {
      try
      {
        conn.close();
      }
      catch(Exception innerex){ innerex.printStackTrace(); }
    }
    
 
  }
  
  OracleConnection connect() throws SQLException
  {
    OracleDriver dr = new OracleDriver();
    Properties prop = new Properties();
    prop.setProperty("user",DBChangeNotification.USERNAME);
    prop.setProperty("password",DBChangeNotification.PASSWORD);
    return (OracleConnection)dr.connect(DBChangeNotification.URL,prop);
  }
}

class DCNDemoListener implements DatabaseChangeListener
{
  DBChangeNotification demo;
  DCNDemoListener(DBChangeNotification dem)
  {
    demo = dem;
  }
  public void onDatabaseChangeNotification(DatabaseChangeEvent e)
  {
    Thread t = Thread.currentThread();
    System.out.println("DCNDemoListener: got an event ("+this+" running on thread "+t+")");
    System.out.println(e.toString());
    System.out.println("---------------");

 
    synchronized( demo ){ demo.notify();}
  }
}