我正在开发一个需要将信息存储到数据库的应用程序.我想尽可能使用Scala解决方案.如果由于某种原因数据库连接失败,我想将原本已执行的sql语句写入.sql脚本文件.我的想法是,当/如果恢复与数据库的连接时,我想在Scala / Java中执行该脚本以使数据库恢复同步.如果程序出现故障,也可以使用.sql脚本,这样就可以手动执行脚本.
如何将我要执行的sql语句记录到Scala / Java中的文件中?那么,如何在Scala / Java中执行该文件(或任何.sql脚本)?
解决方法:
您可以代理您的Connection对象:
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);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。