将参数从一个PreparedStatement复制到另一个

时间:2013-03-21 11:44:47

标签: java jdbc copy prepared-statement

我创建了一个新的PreparedStatement:

PreparedStatement newPs = origPrepStatement.getConnection().prepareStatement("EXPLAIN " + sql);

origPrepStatement也是Prepared语句,它包含参数。 我想将origPrepStatement的参数复制到newPs。 有没有办法做到这一点?

1 个答案:

答案 0 :(得分:0)

似乎没有简单的解决方案;在下面找到我笨拙的解决方案

class PreparedStatementParameters implements InvocationHandler {
    Map<Integer, Object> map = new HashMap<>();
    PreparedStatement ps;

    PreparedStatementParameters(PreparedStatement ps) {
        this.ps = ps;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (method.getName().startsWith("set")) {

        }
        return method.invoke(proxy, args);
    }

    public void copyParameters(PreparedStatement ps) throws SQLException {
        for (Map.Entry<Integer, Object> e : map.entrySet()) {
            ps.setObject(e.getKey(), e.getValue());
        }
    }
}

public class T2 {
    public static void main(String[] args) throws Exception {
        PreparedStatement ps1 = ...
    PreparedStatementParameters ps1params = new PreparedStatementParameters(ps1);
        PreparedStatement ps1Proxy = (PreparedStatement) Proxy.newProxyInstance(null,
                new Class[] { PreparedStatement.class }, new PreparedStatementParameters(ps1));
        ps1Proxy.setString(1, "test");
        ...
        PreparedStatement ps2 = ...
        ps1params.copyParameters(ps2);
    }
}