Is it advisable to return ResultSet?

Hi,
I am studying one java code to enhance its performance.
In that code,
there is one method called getAccountingLines() that returns ResultSet.
This method is called at different 8 places in the entire code.
// pseudo code for getAccountingLine method
private ResultSet getAccountingLines(String fsDocCD, String fsDocDeptCd, String fsDocId, String fsDocVersNo, String fsTableName, String fsVendCustCd)
ResultSet lrs = null;
StringBuffer loQuery = new StringBuffer(1440);
Form the Select query(large in size) and assign it to loQuery.
try
lrs = (ResultSet)( moSession.getResultSetBySQL (loQuery.toString(),
moSession.getDataServerForObject(fsTableName),100));
return lrs
catch (Exception E)
System.err.println("Error Executing Query for getting the Accounting Lines information");
return null;
// code where getAccounting method is called
private void processStmtDetVectors(Vector fvStmtDetPABL, Vector fvStmtDetCC, Vector fvStmtDetPYM,
boolean fbCanAddToHist, R_ADImpl foAd, String fsBillLocCd,boolean fbCanAddToDet,String fsStmtType) throws Exception
ResultSet loResSet = null;
try
loResSet = getAccountingLines(lsDocCd,lsDocDeptCd,lsDocId,lsDocVersNo,"RE_DOC_ACTG",lsVendCustCd);
if (loResSet != null)
catch(Exception e)
finally
if (loResSet!=null )
loResSet.close();
Now my question is :
Is the reference of ResultSet instance(lrs) of getAccountingLine() method is closed with ResultSet instance(loResSet) of callee method(processStmtDetVectors) closed.
What I understand from above is references of ResultSet instance(lrs) of getAccountingLine() method are not closed with ResultSet instance(loResSet) of callee method(processStmtDetVectors) closed. If it remains open, it can creat memory problems.
Is it advisable to return ResultSet?
I think, method should return String (Query Statement) and at the place where method called, query should fire.
Let me know whether my understanding regarding this is true or not.
Anything else if any one can add to this, please let me know.
This will be very helpful to me.
Thanks in advance,
Deepalee

As a general rule, no, there is nothing wrong with returning a ResultSet (I do it myself all the time). You just have to be careful not to access it after the Statement or Connection go out of scope or are closed. If you do, you're liable to get a NullPointerException or something equally nasty.

Similar Messages

  • Help! Need oracle help with constructing stored procedure that return resultsets

    Suns tutorial path for returning resultsets from stored procedures indicates that the following should work...
    CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}");
    ResultSet rs = cs.executeQuery();
    Thats if you build your stored procedure something like this ...
    String createProcedure = "create procedure SHOW_SUPPLIERS " + "as " + "select SUPPLIERS.SUP_NAME, COFFEES.COF_NAME " + "from SUPPLIERS, COFFEES " + "where SUPPLIERS.SUP_ID = COFFEES.SUP_ID " + "order by SUP_NAME";
    We are using oracle 8.1.6. However I've been told that with oracle procedures when you return a result set from a called procedure you return a p_cursor variable. Somthing like this
    (p_cursor in out SHOW_SUPPLIERS.SHOCurTyp)
    is
    begin
    open p_cursor for
    select * from suppliers
    In which case the above mentioned sun code doesn't work.
    We want to use jdbc to call a stored procedure that returns a resultset that does not require us to import any proprietary oracle objects...
    Is there another way to write these stored procedures, rather than using this cursor construct? Are we missing something in the way we invoke them?

    Suns tutorial path for returning resultsets from stored procedures indicates that the following should work...
    CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}");
    ResultSet rs = cs.executeQuery();
    Thats if you build your stored procedure something like this ...
    String createProcedure = "create procedure SHOW_SUPPLIERS " + "as " + "select SUPPLIERS.SUP_NAME, COFFEES.COF_NAME " + "from SUPPLIERS, COFFEES " + "where SUPPLIERS.SUP_ID = COFFEES.SUP_ID " + "order by SUP_NAME";
    We are using oracle 8.1.6. However I've been told that with oracle procedures when you return a result set from a called procedure you return a p_cursor variable. Somthing like this
    (p_cursor in out SHOW_SUPPLIERS.SHOCurTyp)
    is
    begin
    open p_cursor for
    select * from suppliers
    In which case the above mentioned sun code doesn't work.
    We want to use jdbc to call a stored procedure that returns a resultset that does not require us to import any proprietary oracle objects...
    Is there another way to write these stored procedures, rather than using this cursor construct? Are we missing something in the way we invoke them?

  • Return ResultSet Method

    What am I doing wrong to get a "cannot return symbol" error? The code is:
    public ResultSet dataSet(){
         String DRIVER="com.mysql.jdbc.Driver";
         try {
         Class.forName(DRIVER);
              //get a recordset;
              Connection conn = DriverManager.getConnection ("jdbc:mysql://localhost/fms");
              Statement stmt = conn.createStatement ();
              ResultSet rset = stmt.executeQuery ("select * from filename");
              //return rset;
         catch(Exception e){
         System.out.println(e);
         return rset;
         }

    easy, because the declaration of rset is only in scope inside the try block.
    once you leave it's out of scope.
    that might be a good thing, because you really don't want to return a ResultSet. Better to load that info into an object or data structure and close the ResultSet immediately in a finally block.
    Lots of bad things in your code:
    (1) Hard-wired driver and URL - should externalize
    (2) You don't close your Connection, Statement, or ResultSet.
    (3) Print the stack trace in the catch block, it might actually help you figure out any problems.
    (4) No connection pooling.
    %

  • Returning ResultSet to jsp from servlet

    Hi,
    I am trying to return a ResultSet (generated in servlet) to a jsp page, but get a "java.lang.ClassCastException" error. Here is my description of what i'm doing....
    I have a search screen (SearchInventory.jsp) that the user goes to to perform the search based on a few variables. When the search button is clicked, i go to a servlet (SearchInventory.java) which gets a ResultSet. In the servlet, i am storing the ResultSet into a bean object, and finally use the RequestDispatcher to redirect to the .jsp page. (and get the "java.lang.ClassCastException" error).
    Here is the relevant code from all parts of the app:
    SearchInventory.java:---------------------------------------------------------------------
    SearchBean sbean=new SearchBean();
    String QueryStr="select ProdName from products";
    Statement stmt=conn.createStatement();
    rs=stmt.executeQuery(QueryStr);
    sbean.setSearchRS(rs);
    req.getSession(true).setAttribute("s_resbean",sbean);
    HttpSession session=req.getSession(true);
    session.setAttribute("s_resbean",rs);
    req.setAttribute("sbean",rs);
    String url="/SearchInventory.jsp";
    RequestDispatcher dispatcher=getServletContext().getRequestDispatcher(url);
    dispatcher.forward(req,res);
    SearchBean.java:
    public class SearchBean extends HttpServlet{
    private int searchFlag=0;
    private static ResultSet searchRS;
         public void setSearchRS(ResultSet rs){
              this.searchRS=rs;
    And finally, the .jsp page..SearchInventory.jsp:
    <%@ page language="java" import="java.lang.*,java.sql.*,javax.sql.*,PopLists.PopInvLists,beans.SearchBean"%>
    <jsp:useBean scope="session" id="s_resbean" class="beans.SearchBean" />
    ResultSet search=(ResultSet)request.getAttribute("s_resbean");
    If i don't cast it to type ResultSet, i get the following error, which leads me to believe that i should be casting it to a Result Set.
    C:\Apache\tomcat_4.1.29\work\Standalone\localhost\DBTest\SearchInventory_jsp.java:75: incompatible types
    found : java.lang.Object
    required: java.sql.ResultSet
    ResultSet search=request.getAttribute("s_resbean");
    Please help...
    Thanks in advance,
    Aditya.

    Yikes...i realized some of my many problems...i'm using setAttribute multiple times here...(shown by arrows at the end)
    sbean.setSearchRS(rs);
    req.getSession(true).setAttribute("s_resbean",sbean);//<--
    HttpSession session=req.getSession(true);
    session.setAttribute("s_resbean",rs);//<--
    req.setAttribute("sbean",rs);//<--
    I've tried using one at a time since, and it still doesn't work. How exactly should i be setting the attribute. I don't think any of the methods listed above are completely correct...cause it's never worked!:(
    Is anything that i've done correct? (ie. bean/jsp). I'm really starting to doubt myself now. I've been reading up on this, and some people say that one shouldn't return a ResultSet to the jsp, but instead return an ArrayList. Is this correct? If so, how do i convert an ResultSet to an ArrayList?
    -Aditya.

  • Pass variables and return ResultSet from same preparedStatement

    I am passing "fp" and "week_no" to a preparedStament in a class and want to return the values to my jsp page. "fp" and "week_no" are used twice. Please see below. When I run it, I get no error messages but, it doesn't display any data.
    I have the following code in a class:
    public ResultSet getHistory(String fp, String week_no)
                        throws SQLException, Exception {
    ResultSet rs = null;
    if (con != null) {
    try {
         PreparedStatement getHist;
         getHist = con.prepareStatement(
         "SELECT sbu, TO_CHAR(((sum_dollar) + (adj_sum_dollar)),'$999,999,999.99') AS sum_dollar, TO_CHAR(actual_date,'MM/DD/YY') AS actual_date, " +
         "((sum_cases) + (adj_sum_cases)) AS sum_cases, " +
         "((new_order_cases) + (adj_new_order_cases)) AS new_order_cases, " +
         "((total_open_orders) + (adj_total_open_orders)) AS total_open_orders, " +
         "((back_orders) + (adj_back_orders)) AS back_orders, " +
         "TO_CHAR((sum_dollar/sum_cases), '999.99') AS yield " +
         "FROM SUMMARY " +
         "WHERE actual_date BETWEEN (SELECT begin_dt " +
                   "FROM fiscal_calendar " +
                             "WHERE fiscal_period = '?' " +
                             "AND week_number = '?' " +
                             "AND week_number <> '9' " +
                             "AND fiscal_yr = '2003') " +
                        "AND " +
                             "(SELECT end_dt " +
                        "FROM fiscal_calendar " +
                             "WHERE fiscal_period = '?' " +
                             "AND week_number = '?' " +
                             "AND week_number <> '9' " +
                             "AND fiscal_yr = '2003') " +
              "ORDER BY actual_date, sbu ");
         getHist.setString(1, fp);
         getHist.setString(2, week_no);
         getHist.setString(3, fp);
         getHist.setString(4, week_no);
         rs = getHist.executeQuery();
         } catch (SQLException sqle) {
    error = "SQLException: Update failed, possible duplicate entry.";
         throw new SQLException(error);
    } else {
    error = "Exception: Connection to the database was lost.";
         throw new Exception(error);
    return rs;
    This is in my jsp:
    <%
    String fp = request.getParameter("fp");
    String week_no = request.getParameter("week_no");
    historyInfo.connect();
    ResultSet rs = historyInfo.getHistory(fp, week_no);
    while (rs.next()) {
    //String sum_dollar = rs.getString("sum_dollar");
    %>
    <%= rs.getString("sum_dollar") %>
    <%
    %>

    Hi,
    First thing U can't do this way in java. If U are executing this sort of database query, after retriving all the values, put inside Haahtable or HashMap as the application required and return it.
    Otherwise execute this query at the same place where u r printing values in jsp page insted of writing it inside seperate method..It will work.
    If still it's not workimg, please let me know.
    Rajeh Pal

  • Returning ResultSet data

    i want my class to return data to another class. I know i cant return a ResultSet because my connection closes. Can i return some collection similar to a ResultSet ( something 2 dimensional). Can i return metadata from this class?
    thanx

    A typical solution is to return an ArrayList (or some other datatype) that contains several objects, each containing the data from the row. For example, if I wanted to return a username/password combination, you can create a User class that simply holds those two values, then each iteration through your ResultSet, create a new object, put the two values in it, and stick it in your ArrayList.
    This is probably the most effective way, since any datastructure is generally intended to handle data of a certain type, and since data from your database is most likely varying in types, creating one two-dimensional datastructure is probably not going to be as effective.

  • Returning ResultSets to jsp

    Hi,
    I'm using a javabean that returns a resultset from oracle and i need that resultset to execute another query so i can return the data to a jsp. My problem is it will only execute through a while loop once as i have passed it to a String. Does anyone have any idea how i could go about this? So far I've been using while loops eg.
         result = select.executeQuery("select * from score where stu_score = 10 and level_id = 1");
              while(result.next())      
    String s = result.getString("stu_id");
    System.out.println(s);
    result = select.executeQuery("Select stu_name from Student where stu_id = '"+s+"'");
    while(result.next())
         String r = result.getString("stu_name");
         System.out.println(r);
    This will return one stu_id and one stu_name. Any ideas?

    Hi,
    You are getting results from the database and storing them in result. Inside your outermost while loop you are overwriting the same object i.e. result, by saying
    result = select.executeQuery("Select stu_name from Student where stu_id = '"+s+"'");
    That is why you only get one stu_id and one stu_name. Outside the first while loop, declare another ResultSet object, call it result2, and use that one inside.
    However, I strongly recommend not to run such code in a jsp. Do this in a servlet, and set your results that you get through the resultsets in a data transfer object, store it in the request or session, and then get it in the jsp. Also, remeber to close your resultset, statment, and connection objects, otherwise you will suffer from the open cursors problem - eventually! And above all, that is the right way of doing stuff.
    Hope this helps.

  • Returning Resultsets in EJB

    Hi ,
    I want to return the resultset of a database query through an EJB (Stateless Session bean). However as per EJB specs, since a resultset is not serializable so it can not be returned directly. I read that sun provides a CachedRowSet for this purpose. However I am unable to locate the class/package file for this. If anyone of you can provide me a link to the file, it will be a big help to me.
    Another solution I found was to convert the resultset into a collection(HashMap or ArrayList) and then return that. Which one is better- HashMap or ArrayList?
    If there is any other better solution, please let me know.
    Thanks in advance!!
    regards,
    Manish

    RowSet is part of J2SE 5.0 (previously 1.5).
    You can download the rowset reference implementation from http://java.sun.com/products/jdbc/download.html#rowset1_0_1
    I have used ArrayList myself, but you can easily test the performance in your case to see which is more efficient.

  • Return ResultSet via RMI

    Hello all,
    I understand that it is not possible to return a ResultSet via RMI, correct?
    I have a query that I want to use its recordset and this recordset would then be used as an argument for my TableModel to create the data.
    How can I use a vector or arrayList to transfer the ResultSet via RMI?
    Here's my secenario:
    ==== View.java ==============
    ResultSet rsData = getModel().viewRecord(sortString);
    myTable.setModel(getModel().getMyTableModel(rsData));
    myTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    ==== Model.java ==============
    public ResultSet viewRecord(String query) {
    try {
    return getDBStatement().executeQuery( query ); <--- instead of this..
    what do I have to do here to return it as a Vector or arrayList
    catch ( SQLException e ) {
    e.printStackTrace();
    return null;
    How do I use RMI to get the record set back and read it for my View?
    Thanks,
    Christopher

    Hello lgurevich ,
    Please forgive me my crazy questions as I'm just starting to learn and implement about RMI.
    Can you or anyone else provide / illustrate to me some specific examples as to how I could do this.
    Here's my logic:
    View - Model (the model is the remote Implementator)
    ====== MyView.java ===========
    String myQuery = "SELECT field1, field2, blah, blah ........ ";
    ResultSet rs = getMyModel().viewRecord(myQuery);
    myTable.setModel(getMyModel().getMyTableModel(rs));
    myTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    ============================
    ======= MyModel.java ===========
    public ResultSet viewRecord(String query) {
    try {
    return getModelDBStatement().executeQuery( query );
    catch ( SQLException e ) {
    e.printStackTrace();
    return null;
    } // end of viewRecord()
    public MyTableModel getMyTableModel(ResultSet r)
    throws SQLException {
         // Create and return my MyTableModel for the ResultSet
         return new MyTableModel(r);
    ============================
    ======== MyTableModel.java ===========
    public class MyTableModel
    extends AbstractTableModel {
    private ResultSet results;
    Vector totalrows = new Vector();
    public MyTableModel(ResultSet rs) throws SQLException {
    this.results = rs;
    ResultSetMetaData rsmd = rs.getMetaData();
    int columns = rsmd.getColumnCount();
    headers = new String[columns];
    for (int i = 0; i < columns; i++) {
    headers[i] = rsmd.getColumnName(i+1);
    /* ** Create a list of the column data */
    while (rs.next())
    String[] record = new String[columns];
    for (int i = 0; i < columns; i++) {
         record[i] = rs.getString(i+1);
    totalrows.addElement( record );
    } // end of MyTableModel class
    ============================
    So basically, what I'm asking is how do I implement the CachedRowSet to replace the logic of what I have here?
    That is:
    1. To send the query from my view to my model
    2. Model processes the query
    3. Model creates the resultset
    4. Model puts the resultset in the CachedRowSet?
    5. Model sends the CachedRowSet? back to the View.
    6. The View then deserializes? the CachedRowSet? back to a resultset object.
    7. Should I even need to do step 6 considering, I have to send it back to the Model immediately so i could set my TableModel (ie. myTable.setModel(getMyModel().getMyTableModel(rs)); ).
    Any help is greatly appreciated.
    Thanks,
    Christopher

  • Returning resultset to a list

    I am trying to return my resultset to a List of Integers, but the example i am following uses a list of doubles. I have been getting on ok with with this untill i came to this point
    while (rs.next()) { int result = rs.getInteger(1); topTimes.add(result); }
    The getInteger method requires a system property as a parameter. What is a system property?

    I actually made a silly error, which is why i was being returned with the wrong values. I had the result field set to text instead of number. Thats just about me done with this problem now, after about 2 months! The final thing is one error i am being returned on the command line after i receive the results. I have done everything in one method as i have other quiries in this class.
    public void getFastest() 
    String SELECT_TOP_TIMES =
    "select TOP 3 r.result " +
    "from tblResults as r " +
    "where r.Event_ID = " +
    "(select e.ID " +
    "from tblEvent as e " +
    "where e.Event_Name = '100M Run') " +
    "and r.Round_ID = " +
    "(select ro.ID " +
    "from tblRound as ro " +
    "where ro.Round_Number = 'Round_1') " +
    "order by r.result";
    PreparedStatement ps = null;
    ResultSet rs = null;
    List<Integer> topTimes = new ArrayList<Integer>();
    try
    con = DatabaseUtils.connect(DRIVER, URL); 
    ps = con.prepareStatement(SELECT_TOP_TIMES);
    rs = ps.executeQuery();
    while (rs.next())
    int result = rs.getInt(1);
    topTimes.add(result);
    System.out.println(topTimes);
    catch(Exception e)
    System.out.println(e);
    DatabaseUtils.rollback(con);
    e.printStackTrace();
    finally
    DatabaseUtils.close(ps);
    DatabaseUtils.close(rs);
    DatabaseUtils.close(con);
    }But with it set like this, i get returned this message in my command prompt
    [3, 4, 32]
    java.sql.SQLException: ResultSet is closed
            at sun.jdbc.odbc.JdbcOdbcResultSet.checkOpen(JdbcOdbcResultSet.java:6646
            at sun.jdbc.odbc.JdbcOdbcResultSet.clearWarnings(JdbcOdbcResultSet.java:
    1765)
            at sun.jdbc.odbc.JdbcOdbcResultSet.close(JdbcOdbcResultSet.java:1468)
            at DatabaseUtils.close(DatabaseUtils.java:41)
            at DatabaseSQL.getFastest(DatabaseSQL.java:143)
            at Meet.exit_actionPerformed(Meet.java:440)
            at Meet.access$600(Meet.java:9)
            at Meet$7.actionPerformed(Meet.java:183)
            at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:19
    95)
            at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.jav
    a:2318)
            at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel
    .java:387)
            at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242
            at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonL
    istener.java:236)
            at java.awt.Component.processMouseEvent(Component.java:6041)
            at javax.swing.JComponent.processMouseEvent(JComponent.java:3265)
            at java.awt.Component.processEvent(Component.java:5806)
            at java.awt.Container.processEvent(Container.java:2058)
            at java.awt.Component.dispatchEventImpl(Component.java:4413)
            at java.awt.Container.dispatchEventImpl(Container.java:2116)
            at java.awt.Component.dispatchEvent(Component.java:4243)
            at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322
            at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
            at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
            at java.awt.Container.dispatchEventImpl(Container.java:2102)
            at java.awt.Window.dispatchEventImpl(Window.java:2440)
            at java.awt.Component.dispatchEvent(Component.java:4243)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
            at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThre
    ad.java:273)
            at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.
    java:183)
            at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.
    java:177)
            at java.awt.Dialog$1.run(Dialog.java:1045)
            at java.awt.Dialog$3.run(Dialog.java:1097)
            at java.security.AccessController.doPrivileged(Native Method)
            at java.awt.Dialog.show(Dialog.java:1095)
            at java.awt.Component.show(Component.java:1422)
            at java.awt.Component.setVisible(Component.java:1375)
            at java.awt.Window.setVisible(Window.java:806)
            at java.awt.Dialog.setVisible(Dialog.java:985)
            at CreateAtlDatabase.CreateAtlDatabase_actionPerformed(CreateAtlDatabase
    .java:110)
            at CreateAtlDatabase.access$000(CreateAtlDatabase.java:8)
            at CreateAtlDatabase$1.actionPerformed(CreateAtlDatabase.java:67)
            at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:19
    95)
            at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.jav
    a:2318)
            at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel
    .java:387)
            at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242
            at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonL
    istener.java:236)
            at java.awt.Component.processMouseEvent(Component.java:6041)
            at javax.swing.JComponent.processMouseEvent(JComponent.java:3265)
            at java.awt.Component.processEvent(Component.java:5806)
            at java.awt.Container.processEvent(Container.java:2058)
            at java.awt.Component.dispatchEventImpl(Component.java:4413)
            at java.awt.Container.dispatchEventImpl(Container.java:2116)
            at java.awt.Component.dispatchEvent(Component.java:4243)
            at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322
            at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
            at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
            at java.awt.Container.dispatchEventImpl(Container.java:2102)
            at java.awt.Window.dispatchEventImpl(Window.java:2440)
            at java.awt.Component.dispatchEvent(Component.java:4243)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
            at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThre
    ad.java:273)
            at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.
    java:183)
            at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThre
    ad.java:173)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
            at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)Do i need to set up the List in its own method and then pass the resultset to this method?

  • How to return ResultSet from one function to another?

    Hi friends,
    Greetings.
    How do we pass the query Results from one function to another function?
    Actually i have a database in the server and i am the client.
    Client sends the id to the server as an argument. From HTML file this goes to the JSP file(which i am using as a link between HTML and EJB) and then this goes to the RemoteInterface and then to the Bean itself. The functions are written in the bean. Bean connects to the database using jdbc:odbc driver and then a query is written and executed as follows:
    In the Stateless Session Bean, there is one function with the following query.
    public ResultSet check(String id)
    //other code
    ResultSet rs = Statement.("select * from table1 where id=123");
    if(!rs.next)
    // print no such id exists. other ids are
    rs=Statement.("select * from table1");
    return rs;
    I have written it approximately only because the problem is not with the query :(
    Now, in rs there's a resultset. Now how do i display it in a tabular format in HTML? This should obviously be done using JSP. How can we do it?
    In JSP file if i write
    ResultSet rs1=Remote.check(12);
    i get NullPointerException
    Thank you in anticipation to your reply!
    Regards

    Crossposted over all places:
    [http://forums.sun.com/thread.jspa?threadID=5336533]
    [http://forums.sun.com/thread.jspa?threadID=5336534]
    [http://forums.sun.com/thread.jspa?threadID=5336532]
    [http://forums.sun.com/thread.jspa?threadID=5336519]
    [http://forums.sun.com/thread.jspa?threadID=5336510]
    Stop crossposting. It's very rude.

  • Return Resultset from Procedure

    Hi --
    This may seem like a very elementary question, but can anyone tell me how to return a resultset from a function or procedure?
    Thanks,
    Christine

    if i understand your question correctly. a function return value is mandatory. while procedure is optional you had to use the out at the parameters. examples:
    CREATE OR REPLACE FUNCTION get_age (pBday Date) RETURN number IS
      vAge          Number := 0;
    BEGIN
      vAge := (Months_Between(sysdate,pBday) / 12);
      Return (vAge);
    END;
    CREATE OR REPLACE PROCEDURE get_age_procedure (pBday In Date, pAge Out Number) IS
    BEGIN
      pAge := (Months_Between(sysdate,pBday) / 12);
    END;
    /you need to create a reference cursor type object to achieve a result sets.
    CREATE OR REPLACE package TYPES AS
        TYPE cursorType IS REF CURSOR;
    END;

  • Returning Resultset from different DB

    Hi folks,
    I am working on a developing a Database Framework. The user gives information about the stored proc to execute,parameters required by the stored prc, the connection url ,credentials and database provider(which can be Oracle,SQL Server or DB2). I have to execute the query and return back the resultset to the user.
    What I am interested in knowing is does each and every DB provider handles or create the ResultSet in different way?
    For Example:
    In oracle the Stored proc call looks like setting a registerOutParameter and then getting the ResultSet:
    String query = "{call ? := myStoredProc(?)}";
    CallableStatement stmt = conn.prepareCall(query);
    // register the type of the out param - an Oracle specific type
    stmt.registerOutParameter(1, OracleTypes.CURSOR);
    // set the in param
    stmt.setFloat(2, price);
    // execute and retrieve the result set
    stmt.execute();
    ResultSet rs = (ResultSet)stmt.getObject(1);And in SQL Server I can directly get the ResultSet by doing
    ResultSet rs = stmt.executeQuery();Also the query string will be different i.e.
    String query = "{call myStoredProc(?)}"DB2 will be same as Oracle I guess.
    So my question is , is there any generic way to get the ResultSet???
    Sorry if it sounds a dumb question.I am new to this arena..
    Thanks in advance
    Pankaj

    DB2 will be same as Oracle I guess.No. Getting the resultset in DB2 looks the same as that for SQL Server. Oracle is the only one that has a slightly different code.

  • Returning resultSet from java function

    Hello,
    I have created one function which throws query to database and creates a resultset based on that query.
    I am trying to print the status of database i.e.,
    System.out.println(rs.next());This gives me result : true.
    I am then returning this resultSet to main function and doing the same thing :
    System.out.println(rs.next());but this time it gives me result : false.
    There are total 12 rows in this resultSet and i am not giving rs.next in any loops
    I would like to answer your further query,
    but i am eager to know the reason behind this.
    Thank you

    <BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by Jonathan Roberts ([email protected]):
    Hi.
    Does anyone know what the syntax is for using java stored procedures or functions for returning a rowset.
    This includes the java in the java-sql and the java-procedure definition.
    Cheers
    Jonathan<HR></BLOCKQUOTE>
    null

  • Returning resultset from procedure...or pkg

    I am a newbie to Oracle but am steeped in MSSQL. I am accustomed to using a procedure to execute and produce a result set as its output from various input parameters thus keeping query complexity and details as a part of the database tier.
    Is there a best practice in Oracle that provides this capability? Is the 'ref cursor' the correct container to hold the recordset data (usually combined from various base tables...counts and sums for reports etc) and how should it be returned to a calling application (web page) to be iterated through? Perhaps as an output parameter?
    Thank you for helping with such a basic problem.

    Yes you would use a ref cursor, though it does not hold the results anywhere, they are fetched as needed, which is why it scales well.
    Re: OPEN cursor for large query
    Re: cursor ,inner join
    You can return a ref cursor from a function or procedure, it would be no different in a package.
    SQL> create or replace function f (p_deptno in number)
      2  return sys_refcursor as
      3    c sys_refcursor;
      4  begin
      5    open c for
      6      select empno, ename, job, sal from emp
      7        where deptno = p_deptno;
      8    return c;
      9  end;
    10  /
    Function created.
    SQL> var c refcursor
    SQL> exec :c := f(10)
    PL/SQL procedure successfully completed.
    SQL> print c
    EMPNO ENAME      JOB          SAL
      7782 CLARK      MANAGER     2450
      7839 KING       PRESIDENT   5000
      7934 MILLER     CLERK       1300
    SQL> create or replace procedure p
      2    (p_deptno in number, p_c out sys_refcursor)
      3  as
      4  begin
      5    open p_c for
      6      select empno, ename, job, sal from emp
      7        where deptno = p_deptno;
      8  end;
      9  /
    Procedure created.
    SQL> exec p(30, :c)
    PL/SQL procedure successfully completed.
    SQL> print c
    EMPNO ENAME      JOB          SAL
      7499 ALLEN      SALESMAN    1600
      7521 WARD       SALESMAN    1250
      7654 MARTIN     SALESMAN    1250
      7698 BLAKE      MANAGER     2850
      7844 TURNER     SALESMAN    1500
      7900 JAMES      CLERK        950
    6 rows selected.
    SQL>There are examples how to reference them in other languages here, note this was pre-9i when the built in sys_refcursor type was provided.
    http://asktom.oracle.com/tkyte/ResultSets/index.html

Maybe you are looking for