import java.sql.*;

public class test {

  public static void main(String[] p_args) {
    try {
      Class.forName("org.postgresql.Driver");
      Connection l_conn;
      l_conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/files", "blind", "");
      l_conn.setAutoCommit(false);
      Statement l_stmt = l_conn.createStatement();
      try {
        l_stmt.execute("drop function testcursor()");
      } catch (SQLException l_se) {
	  //ignore failures to drop
      }
      l_stmt.execute(" create function testcursor() returns refcursor as "
                     + "'declare "
                     + "   l_cursor refcursor; "
                     + " begin "
                     + "   open l_cursor for execute "
                     + " ''select 1, ''''foo'''' union all select 2, ''''bar'''' union all select 3, ''''baz'''' ''; "
                     + "   return l_cursor; "
                     + " end; "
                     + "' language plpgsql ");
      l_conn.commit();

      ResultSet l_rset = l_stmt.executeQuery("select testcursor()");
      l_rset.next();
      String l_cursor = l_rset.getString(1);
      System.out.println("Cursor name = " + l_cursor);
      ResultSet l_rset2 = l_stmt.executeQuery("fetch all from \"" + l_cursor + "\"");
      while (l_rset2.next()) {
        int l_intValue = l_rset2.getInt(1);
        String l_strValue = l_rset2.getString(2);
        System.out.println("Values from cursor = " + l_intValue + ", " + l_strValue);
      }
      l_rset2.close();
      l_rset.close();
      l_stmt.close();
    } catch (Exception l_se) {
      System.out.println(l_se.toString());
    }

  }

}


