代码之家  ›  专栏  ›  技术社区  ›  BenjaminJackman

通过从Scala/Java编写/执行SQL脚本处理间歇性数据库连接

  •  4
  • BenjaminJackman  · 技术社区  · 16 年前

    1 回复  |  直到 16 年前
        1
  •  4
  •   dfa    16 年前

    public class ConnectionProxy {
    
        public ConnectionProxy(Object anObject) {
            super(anObject);
        }
    
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {              
            Object result = method.invoke(target, args);
            String methodName = method.getName();
    
            if (methodName.equals("createStatement")) {
                result = ProxyBuilder.createProxy(result, new StatementProxy(result));
            }
    
            return result;
        }
    } 
    

    为了拦截任何对 Statement.execute(String sql) :

    public class StatementProxy {
    
        public StatementProxy(Object anObject) {
            super(anObject);
        }
    
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {               
           try {
               return method.invoke(proxy, args);
           } catch (SQLException sqle) {
               if (method.getName().contains("execute")) {
                  String sql = "";
    
                  if (args != null && args[0] != null) {
                      sql = args[0].toString();
                  }
    
                  saveToFile(arg);
               }
    
               throw sqle;   
            }
        }
    }
    

    public final class ProxyBuilder {
    
        public static Connection tracingConnection(Connection connection) {
            return createProxy(connection, new ConnectionProxy(connection));
        }
    
        static <T> T createProxy(T anObject, InvocationHandler invocationHandler) {
            return createProxy(anObject, invocationHandler, anObject.getClass().getInterfaces());
        }
    
        static <T> T createProxy(T anObject, InvocationHandler invocationHandler, Class... forcedInterfaces) {
            return (T) Proxy.newProxyInstance(
                anObject.getClass().getClassLoader(),
                forcedInterfaces,
                invocationHandler);
            }
    }
    

    当然 这不是您的最终生产代码

    推荐文章