2009-09-29 84 views

回答

0

所有的Java类都是从Groovy中使用。如果Groovy没有给你一个方法去做,那么你可以使用JDBC callable statements来实现Java方式。

0

我只是碰到什么可能是你的问题的解决方案迷迷糊糊的,如果一个例子是,你是什么之后,看看the reply to this thread

2

我写了一个帮手,让我用存储过程的工作,以与使用groovy.sql.Sql的查询类似的方式返回单个ResultSet。这可以很容易地适应处理多个ResultSet(我假设每个都需要它自己的闭包)。

用法:

Sql sql = Sql.newInstance(dataSource) 
SqlHelper helper = new SqlHelper(sql); 
helper.eachSprocRow('EXEC sp_my_sproc ?, ?, ?', ['a', 'b', 'c']) { row -> 
    println "foo=${row.foo}, bar=${row.bar}, baz=${row.baz}" 
} 

代码:

class SqlHelper { 
    private Sql sql; 

    SqlHelper(Sql sql) { 
     this.sql = sql; 
    } 

    public void eachSprocRow(String query, List parameters, Closure closure) { 
     sql.cacheConnection { Connection con -> 
      CallableStatement proc = con.prepareCall(query) 
      try { 
       parameters.eachWithIndex { param, i -> 
        proc.setObject(i+1, param) 
       } 

       boolean result = proc.execute() 
       boolean found = false 
       while (!found) { 
        if (result) { 
         ResultSet rs = proc.getResultSet() 
         ResultSetMetaData md = rs.getMetaData() 
         int columnCount = md.getColumnCount() 
         while (rs.next()) { 
          // use case insensitive map 
          Map row = new TreeMap(String.CASE_INSENSITIVE_ORDER) 
          for (int i = 0; i < columnCount; ++ i) { 
           row[md.getColumnName(i+1)] = rs.getObject(i+1) 
          } 
          closure.call(row) 
         } 
         found = true; 
        } else if (proc.getUpdateCount() < 0) { 
         throw new RuntimeException("Sproc ${query} did not return a result set") 
        } 
        result = proc.getMoreResults() 
       } 
      } finally { 
       proc.close() 
      } 
     } 
    } 
}