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.
%

Similar Messages

  • 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.

  • Return outside method error

    Help me with the following problem please -
    import java.util.*;
    class TComp implements Comparator
         String a,b;
         public int compare(Object a,Object b);
              int i,j,k;
              String aStr,bStr;
              aStr=a;
              bStr=b;
              i=aStr.lastIndexOf("");
              j=bStr.lastIndexOf("");
              k=aStr.substring(i).compareTo(bStr.substring(j));
              if(k==0)
                        return aStr.compareTo(bStr);
              else
                        return k;
    class TreeMapDemo2
         public static void main(String args[])
              TreeMap<String, Double> tm=new TreeMap<String, Double>(); //new TComp()
              tm.put("John Doe", new Double(3434.14));
              tm.put("Tom Smith", new Double(3434.14));
              tm.put("Jane Baker", new Double(3434.14));
              tm.put("Todd Hall", new Double(3434.14));
              tm.put("Ralph Smith", new Double(3434.14));
              tm.put("Terry Boyle", new Double(-19.14));
              Set set=tm.entrySet();
              Iterator itr=set.iterator();
              while(itr.hasNext())
                   Map.Entry me=(Map.Entry)itr.next();
                   System.out.print(me.getKey()+": ");
                   System.out.println(me.getValue());
              System.out.println();
              double balance=(tm.get("John Doe")).doubleValue();
              tm.put("John Doe", new Double(balance+1000));
              System.out.println("John Doe's new balance: "+tm.get("John Doe"));
    }compiling the above program generate the following error message -
    TreeMapDemo2.java:7:missing method body, or declare abstract
    public int compare(Object a, Object b);
    TreeMapDemo2.java:22: return outside method
    return aStr.compareTo(bStr);
    TreeMapDemo2.java:22: return outside method
    return k;
    3 errors.

    I corrected the whole thing successfully. Thanks to all.
    Here's the correct code.
    import java.util.*;
    class TComp implements Comparator
         //String a,b;
         public int compare(Object a,Object b)
              int i,j,k;
              String aStr,bStr;
              aStr=(String) a;
              bStr=(String) b;
              i=aStr.lastIndexOf("");
              j=bStr.lastIndexOf("");
              k=aStr.substring(i).compareTo(bStr.substring(j));
              if(k==0)
                        return aStr.compareTo(bStr);
              else
                        return k;
    class TreeMapDemo2
         public static void main(String args[])
              TreeMap<String, Double> tm=new TreeMap<String, Double>(); //new TComp()
              tm.put("John Doe", new Double(3434.14));
              tm.put("Tom Smith", new Double(3434.14));
              tm.put("Jane Baker", new Double(3434.14));
              tm.put("Todd Hall", new Double(3434.14));
              tm.put("Ralph Smith", new Double(3434.14));
              tm.put("Terry Boyle", new Double(-19.14));
              Set set=tm.entrySet();
              Iterator itr=set.iterator();
              while(itr.hasNext())
                   Map.Entry me=(Map.Entry)itr.next();
                   System.out.print(me.getKey()+": ");
                   System.out.println(me.getValue());
              System.out.println();
              double balance=(tm.get("John Doe")).doubleValue();
              tm.put("John Doe", new Double(balance+1000));
              System.out.println("John Doe's new balance: "+tm.get("John Doe"));
    }

  • How to connect a graph to a list returned by method?

    Hi
    jdev 11.1.1.5
    How can I connect a graph to a list returned by method???

    This is my problem:
    I have a vo with several column and 2 more column that in these column I use analytic function to count (col1 and col2) .Know this vo return to many records . I want to have 2 graphs base on this column (col1 and col2) and one table base on all columns.
    after drag controler on page as graph because of repeated record with the same value in count column I have not good graph with distinct value.know I want to have a method that return a list or something can iterate and make graph on this .How Can I do ? Is it posible??
    (I use this aproach because do all transaction in one query)

  • Return outside method...

    Hi,
    I've got a problem with a method i'm creating.
    I'm trying it to get it to return the boolean value true. But when i compile it gives me the an error message saying "return outside method".
    Does anybody know what it means?
    Here's my code:
        public boolean printOne(String text) {}
            if(sheet >= 0) {
                copy = copy + 1;
                sheet = sheet - 1;
                return true;
        }

    jverd wrote:
    LevelSix wrote:
    jverd wrote:
    LevelSix wrote:
    By the way here's the question i'm trying to answer.
    MyPrinter needs some printing methods. The first, signature:
    public boolean printOne(String text)+
    should take a String as a parameter, and output it on a single line to the terminal window.
    It should also increment (add 1 to) the total number of copies made, and decrement (subtract 1 from) the number of sheets of paper available.
    It should return the boolean value true(this is actually to avoid confusion in the next assignment)
    Okay, and what particular problem are you having with this?There's two problem..
    How do i get..."*The signature:* *+public boolean printOne(String text)+* *should take a String as a parameter, and output it on a single line to the terminal window.*"?Do you know what a method signature is?
    Do you know how to write a method?
    Do you know how to print something on the terminal?
    You haven't really provided any details about what in particular you're having trouble with. Show your work, and ask a more specific question.
    I'm also trying to do this "*It should return the boolean value true*".So, you don't know how to return a value from a method?I know how to do all that.
    The problem i'm having is probably what i wrote above (in reply to oscarjustesen post).

  • 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?

  • 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 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?

  • Data Control does not show POJO returned from method

    Hi,
    I am running JDev 11.1.1.7. In my AppModule.impl I created a method that returns a simple POJO (which implements serializable) that has two String fields. I have exposed the method in the appmodule client interface. In the data control the method shows up with a return element instead of an object or any way to access the two String fields. I want to display the two String fields in separate output text components on my jspx page. I'm not finding documentation on how to do this. Can somebody point me to documentation or tell me how to make this change to the data control method return?
    Thanks in advance,
    Steve

    AM method can return custom type, but AFAIK there is no support for object introspection in design time.
    (so you can invoke this programmatically and cast to appropriate type, but you can't do DnD from Data Control pane).
    So, option 1 is to bind value property of your outputText fields to managed bean, programmatically call AM method, fill these properties manually and refresh your UI components(note that managed bean must be registered in viewScope or higher to preserve values)
    Option 2 is to create Bean DataControl (with this you will have DnD support)
    Dario

  • Return from method

    Hello, I want to return all three arrays in this method. what�s wrong with this code.tnx
    public int prim(int arr[])
    arr[0] = Integer.parseInt(textField1.getText());
    arr[1] = Integer.parseInt(textField2.getText());
    arr[3] = Integer.parseInt(textField3.getText());
    return arr[];
    }

    You should read the beginnners' tutorials.Resources for Beginners
    Sun's basic Java tutorial
    Sun's New To Java Center. Includes an overview of what Java is, instructions for setting up Java, an intro to programming (that includes links to the above tutorial or to parts of it), quizzes, a list of resources, and info on certification and courses.
    http://javaalmanac.com. A couple dozen code examples that supplement The Java Developers Almanac.
    jGuru. A general Java resource site. Includes FAQs, forums, courses, more.
    JavaRanch. To quote the tagline on their homepage: "a friendly place for Java greenhorns." FAQs, forums (moderated, I believe), sample code, all kinds of goodies for newbies. From what I've heard, they live up to the "friendly" claim.
    Bruce Eckel's Thinking in Java (Available online.)
    Joshua Bloch's Effective Java
    Bert Bates and Kathy Sierra's Head First Java. This one has been getting a lot of very positive comments lately.

  • 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

Maybe you are looking for

  • Automatic change of text size and shape in pages from master

    Hi, I'm new to Indesign and I'm trying to write a long book which is more like a catalog. I've created a book file (.indb) in which various files (.indd) are inserted. Each of these files will represent a chapter. All chapters must have the same aspe

  • How to notify (email) Change Manager when new Change Request is created

    Hi there, I am battling to generate an email when a developer creates a Change Request directly in the SolMan system. When he creates a new Change Request via CRMD_ORDER by filling in the Sold-to-Party, Change Manager, iBase etc., the message is auto

  • Image data uri doesnt work

    i have the following data uri for an image (see http://jsfiddle.net/VnnhS/). it works on every other brower except safari? is it siae limit issue?

  • Weblogic certification 11g 1z0-102

    Looking for a good book to prepare for this exam. Right now I am reading Oracle Weblogic Server 11gR1 PS2: Administration Essentials by Michel Schildmeijer.

  • SAP Downtime through SAP

    Is there is any way to check the SAP downtime through SAP itself. Regard Vishnu