2013-03-21 19 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

相關問題