3

I create a new PreparedStatement like this:

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

origPrepStatement is also Preparedstatement and it contains parameters. I'd like to copy the parameters of origPrepStatement to newPs. Is there away to do that?

Sanyifejű
  • 2,610
  • 10
  • 46
  • 73

1 Answers1

1

There seems to be no easy solution; find my clumsy solution below

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);
    }
}
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275