2013-03-21 73 views
2

我创建一个新的预处理是这样的:参数复制到另一个

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

origPrepStatement也PreparedStatement和它包含的参数。 我想将origPrepStatement的参数复制到newPs。 有没有做到这一点?

+3

入住这里笨拙的解决方案:http://stackoverflow.com/a/4691561/2168879 – NilsH 2013-03-21 11:48:51

+0

那是可悲的:-(我并不需要它来完成调试,我需要它的其他用途 – 2013-03-21 12:16:53

回答

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); 
    } 
} 
+0

。这里会发生什么? if(method.getName()。startsWith(“set”)){ } – 2013-03-22 11:26:48

+0

您在ps1上设置的所有参数都将保存在PreparedStatementParameters – 2013-03-22 15:14:55

相关问题