我正在开发一个需要将信息存储到数据库的应用程序。如果可能的话,我想使用Scala解决方案。如果数据库连接由于某种原因而失败,我希望将本应执行的原始SQL语句写入一个.sql脚本文件。这个想法是,当/如果恢复到数据库的连接时,我希望在Scala/Java中执行该脚本,以使数据库恢复同步。在程序出现故障的情况下有.sql脚本也很好,这样就可以手动执行脚本。
如何将将要执行的sql语句记录到Scala/Java中的文件中?那么,如何在Scala/Java中执行那个文件(或者任何.sql脚本)呢?
发布于 2009-07-15 17:14:53
您可以代理您的连接对象:
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;
}
}
}其中ProxyBuilder是一个简单的助手类:
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);
}
}当然,这不是您的最终产品代码,但它是一个很好的起点。
https://stackoverflow.com/questions/1132593
复制相似问题