【问题标题】:how to run stored procedure from groovy that returns multiple resultsets如何从返回多个结果集的groovy运行存储过程
【发布时间】:2009-09-29 17:25:30
【问题描述】:

我在网上找不到任何这样做的好例子。

有人可以展示如何从 groovy 运行存储过程(返回多个结果集)吗?

基本上我只是想确定存储过程返回多少个结果集..

【问题讨论】:

    标签: groovy


    【解决方案1】:

    我编写了一个帮助程序,它允许我处理返回单个 ResultSet 的存储过程,其方式类似于使用 groovy.sql.Sql 处理查询。这可以很容易地适应处理多个结果集(我假设每个结果集都需要它自己的闭包)。

    用法:

    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()
                }
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      所有 Java 类都可以从 Groovy 中使用。如果 Groovy 没有为您提供方法,那么您可以使用 JDBC callable statements 以 Java 方式进行。

      【讨论】:

        【解决方案3】:

        我刚刚偶然发现什么可能是您问题的解决方案,如果您想要的示例是什么,请查看the reply to this thread

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-04-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多