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.

Similar Messages

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

  • Using return statement in jsp

    Hi all,
    I am using return statement in JSP page after a redirect to stop executing that page. If the data bean is not present then it must go to previous page. When this return statement is executed the previous page is displayed but url in browser remains same. Why it is so ?. Is there any other way to tell a JSP page to stop executing and redirect to another page.
    rgds
    Antony Paul

    Hi Antony,
    do you use the "forward()" method or the "redirect()" method???
    rgds
    Howy

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

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

  • Returning ResultSet from servlet to jsp - java.lang.NullPointerException

    Hey all, i've been stuck on this for too long now...just trying to return a ResultSet from a servlet to jsp page.
    Had a bunch of problems earlier...which i think were fixed but...now i get a "java.lang.NullPointerException" in my jsp page when i try to get elements from the ResultSet object.
    Here is the latest version of my code:
    Servlet:
    String QueryStr="select ProdName from products";
    Statement stmt=conn.createStatement();
    rs=stmt.executeQuery(QueryStr); //get resultset
    sbean.setInventory(rs); //set ResultSet in bean
    req.getSession(true).setAttribute("s_resbean",sbean); //create session/request variable, set to bean
    Bean:
    package beans;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import java.sql.*;
    import javax.sql.*;
    public class SearchBean extends HttpServlet{
         private int searchFlag=0;
         private ResultSet inventory;
         public SearchBean(){
         public int getSearchFlag(){
         return searchFlag;
         public ResultSet getInventory(){
              return inventory;
         public void setInventory(ResultSet rs){
              this.inventory=rs;
         public void setSearchFlag(){
              this.searchFlag=1;
    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 categories=PopInvLists.getCat();
    ResultSet manuf=PopInvLists.getManuf();
    ResultSet supplier=PopInvLists.getSupplier();
    ResultSet cars=PopInvLists.getCars();
    ResultSet search=(ResultSet)request.getAttribute("s_resbean");
    %>
    <%     while(search.next()){
         String pname=search.getString("ProdName");
    %>
    It craps out when i try to loop through the "search" ResultSet.
    I can loop through the rest of the ResultSets no problem....just this one doesn't work because it's set in a servlet, not a simple java class.
    Just to clarify, i am populating some dropdown lists on entry to the screen, which the user will use to perform a search. Once the search btn is clicked, the servlet is called, gets the request info for the search, performs search, and returns the resultset to the original screen. I want to eventually display the result under the search criteria.
    Someone....Please Please please tell me how to get this working...it should be very simple, but i just can't get it to work.
    Thanks in advance,
    Aditya

    req.getSession(true).setAttribute("s_resbean",sbean); //create session/request variable, set to beanHere you add an attribute to the session.
    ResultSet search=(ResultSet)request.getAttribute("s_resbean");Here you try to get the attribute from the request. Naturally it isn't there because you added it to the session, not the request. Despite your comment in the first line of code, a session is not a request. And vice versa.

  • How to return ResultSet object from Bean to JSP

    I have a Java Bean, in it I have ResultSet Object in a method. Now I want to send this ResultSet Object to the JSP.

    very good advice, otherwise you will spread your sql exception handling over way too many places. Keep it centered, so you can be sure to close your connection, statement, resultset again. Otherwise your database and web application might all of a sudden stop responding.

  • 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

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

  • Passing Resultsets to JSP

    Hello,
    I want to know how to represent the results of a databse search via a JSP. Initially, I had all of the databse code(example shown below) in the JSP just to get it working. I now want to move the code into a JavaBean (I know there are numerous other ways but as I am still learning I just want to use a Worker Bean). Whilst the code was in the JSP it was easy to display the data using rs.next() etc etc, but now the code is in the bean how do I pass a resultset back to the JSP. Do I use getProperty some how?
    Any help is appreciated
    Cheers
    Mitch
    <%
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection dbaCon = DriverManager.getConnection
    ("jdbc:odbc:MileEnd", "", "");
    String template = "UPDATE PlayerInfo SET Block = ? WHERE LastName = ? and FirstName = ? and password = ?";
    PreparedStatement pstmt = dbaCon.prepareStatement(template);
    pstmt.setBoolean(1, state);
    pstmt.setString(2, lastName);
    pstmt.setString(3, firstName);
    pstmt.setString(4, password);
    pstmt.executeUpdate();
    if (pstmt != null)
    pstmt.close();
    if (dbaCon != null)
    dbaCon.close();
    %>

    Your example will not generate any ResultSet, it gives you an int value saying that, how many rows have been updated.
    int rowsUpdated=pstmt.executeUpdate();
    return rowsUpdated;
    Suppose if you have a query like 'select a,b,c from table_name where some_condition', then you will get a ResultSet. Instead of returning the ResultSet as it is to the jsp, it is better to put them in an array or Vector or some collection object and return that object. So that you can immediately close the resultset and release the db resources.
    ResultSet rs=st.executeQuery();
    Vector v = new Vector();
    while(rs.next())
    String str[]=new String[3];
    str[0]=rs.getString("a"); //or str[0]=rs.getString(1);
    str[1]=rs.getString("b");
    str[2]=rs.getString("c");
    v.add(str);
    // close all the database resources and then return the vector.
    return v;
    In your jsp, you can get this vector and display the results.
    for(int i=0;i<v.size();i++)
    String str[]=(String[])v.elementAt(i);
    // display str[0],str[1] and str[2]
    Hope this helps.
    Sudha

  • Sample code with more than one ResultSet in JSP

    Hi
    Can anyone give me sample JSP code using crystal reports JRC with more than one ResultSets which works, since mine always seem to be giving error .
    Thank you
    Selvi
    RCAgent5 detected an exception: Cannot modify a read-only collection.
         at com.crystaldecisions.reports.common.e.a.clear(Unknown Source)

    You can access the JRC samples from SDN in the Business Objects Portal.  The link to them can be found [here.|https://smpdl.sap-ag.de/~sapidp/012002523100006008982008E/crxi_r2_jrc_web_smpl.zip]  There is a sample called jrc_resultset_datasource that shows how to pass a result set to a report; you can use this and modify it to allow another result set to be passed in.
    As a note, if you are having issues and believe it is your code, start with the sample and take small steps when adding new functionality so that you can determine where things go wrong.

  • Using getDate for ResultSet in jsp

    Hello,
    In a jsp I'm trying to display a date stored in a mysql database.
    In the jsp i have put the following:
    <TD align='right'>Meeting Date</TD>
    <TD align='right'>
    <INPUT type='text' name='meetingDate' value='<%= rsClients.getDate("meetingDate") %>'</TD>
    </TR>
    rsClients is the ResultSet where I have stored mysql table data.
    But when I run servlet that subsequently fires up jsp to display data stored in mysql database I get the following sql exception:
    java.sql.SQLException: Value '0000-00-00' can not be represented as java.sql.Date
         at com.mysql.jdbc.ResultSet.getDateFromString(ResultSet.java:1913)
         at com.mysql.jdbc.ResultSet.getDate(ResultSet.java:1849)
         at com.mysql.jdbc.ResultSet.getDate(ResultSet.java:1817)
         at com.mysql.jdbc.ResultSet.getDate(ResultSet.java:1865)
         at org.apache.jsp.ProcessClients$jsp._jspService(ProcessClients$jsp.java:154)
    Can anyone explain why I'm getting this error please,
    Cheers Joe.

    I think you have store wrong data in Date Type field in MYsql
    so try to store data in formate of YYYY-MM-DD right now it is 0000-00-00
    Because you have try to enter any No,String or It isnot Correct date Type

  • 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 XMLType to JSP

    Hello, all.
    I have a stored function that returns XMLType data to a JSP page, similar to the example in the Oracle XML DB Developer's Guide (13-4). My schema was developed with great help from this forum and is referenced here:Re: unique constraint defined in xsd
    My problem is I am getting the following error when I try to access the returned data in the jsp page:
    java.lang.ClassCastException: oracle.sql.OPAQUE
         at querymaps.jspService(querymaps.jsp:45)
    I cannot quite figure out how to get to the returned data.
    Here is the stored function and a sample of data the same select statement returns:
    CREATE OR REPLACE FUNCTION getMaps(userName varchar2)
    RETURN XMLTYPE
    AS
    xmlDoc XMLTYPE;
    BEGIN
    SELECT extract(OBJECT_VALUE, '/mapset/map') into xmlDoc
    FROM mapsetxml
    WHERE existsNode(OBJECT_VALUE,'/mapset['''|| username ||''']')=1;
    RETURN xmlDoc;
    END;
    <map>
    <mapname>Florida</mapname>
    <layer>
    <layername>Counties</layername>
    <layerid>counties</layerid>
    <service>base</service>
    <visible>1</visible>
    <ftype>polygon</ftype>
    </layer>
    <placemark>
    <placename>Florida</placename>
    <envelope>
    <minx>-186185.234572</minx>
    <miny>2709914.999735</miny>
    <maxx>596332.812876</maxx>
    <maxy>3464678.999670</maxy>
    </envelope>
    </placemark>
    </map>
    The JSP scriplet code is nearly right from the sample- I am using a dataSource connection, so I don't know if that is the problem, or not.
    <%
    Connection conn=null;
    CallableStatement stmt = null;
    String dSrcName="jdbc/localDS";
    String userName="tester";
    XMLType xmlRes = null;
    InitialContext ctxt = new InitialContext();
    DataSource ds = (DataSource) ctxt.lookup(dSrcName);
    conn = ds.getConnection();
    try {        
    stmt=conn.prepareCall("{ ? = call getmaps(?)}");
    stmt.registerOutParameter(1, OracleTypes.OPAQUE,"SYS.XMLTYPE");
    stmt.setString(2, userName);
    stmt.execute();
    xmlRes = (XMLType) stmt.getObject(1);
    if (xmlRes != null) {
    String mapString = xmlRes.getStringVal();
    out.println("The map xml for :"+userName+" is "+mapString);
    } catch (SQLException se) {
    out.println(se.getMessage());
    } catch (Exception e) {
    out.println(e.getMessage());
    } finally {
    stmt.close();
    conn.close();
    %>
    Thanks again.

    Given the follow
    SQL> var schemaURL varchar2(256)
    SQL> var schemaPath varchar2(256)
    SQL> --
    SQL> begin
      2    :schemaURL := 'http://localhost:8080/public/mapset.xsd';
      3    :schemaPath := '/public/mapset.xsd';
      4  end;
      5  /
    PL/SQL procedure successfully completed.
    SQL> call dbms_xmlSchema.deleteSchema(:schemaURL,4)
      2  /
    Call completed.
    SQL> declare
      2    res boolean;
      3    xmlSchema xmlType := xmlType(
      4  '<?xml version="1.0" encoding="UTF-8" ?>
      5  <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
      6             xmlns:xdb="http://xmlns.oracle.com/xdb"
      7             version="1.0" xdb:storeVarrayAsTable="true">
      8    <!-- definition of simple types -->
      9    <xs:simpleType name="nameType">
    10      <xs:restriction base="xs:string">
    11        <xs:minLength value="1"/>
    12        <xs:maxLength value="50"/>
    13      </xs:restriction>
    14    </xs:simpleType>
    15    <xs:simpleType name="boolType">
    16      <xs:restriction base="xs:unsignedByte">
    17        <xs:minInclusive value="0"/>
    18        <xs:maxInclusive value="1"/>
    19      </xs:restriction>
    20    </xs:simpleType>
    21     <xs:simpleType name="minxType">
    22      <xs:restriction base="xs:string">
    23      </xs:restriction>
    24    </xs:simpleType>
    25     <xs:simpleType name="minyType">
    26      <xs:restriction base="xs:string">
    27      </xs:restriction>
    28    </xs:simpleType>
    29     <xs:simpleType name="maxxType">
    30      <xs:restriction base="xs:string">
    31      </xs:restriction>
    32    </xs:simpleType>
    33     <xs:simpleType name="maxyType">
    34      <xs:restriction base="xs:string">
    35      </xs:restriction>
    36    </xs:simpleType>
    37    <xs:simpleType name="usernameType">
    38      <xs:restriction base="xs:string">
    39        <xs:minLength value="7"/>
    40        <xs:maxLength value="8"/>
    41      </xs:restriction>
    42    </xs:simpleType>
    43    <xs:simpleType name="emailType">
    44      <xs:restriction base="xs:string">
    45        <xs:minLength value="19"/>
    46        <xs:maxLength value="63"/>
    47      </xs:restriction>
    48    </xs:simpleType>
    49     <!-- definition of complex types -->
    50  <xs:complexType name="envType">
    51      <xs:sequence>
    52        <xs:element name="minx"  type="minxType" minOccurs="1" xdb:SQLName="MINX" />
    53        <xs:element name="miny" type="minyType" minOccurs="1" xdb:SQLName="MINY"/>
    54        <xs:element name="maxx"  type="maxxType" minOccurs="1" xdb:SQLName="MAXX" />
    55        <xs:element name="maxy" type="maxyType" minOccurs="1" xdb:SQLName="MAXY"/>
    56      </xs:sequence>
    57    </xs:complexType>
    58   <xs:complexType name="placemarkType">
    59      <xs:sequence>
    60        <xs:element name="placename"  type="nameType" minOccurs="1" xdb:SQLName="PLACENAME"/>
    61        <xs:element name="envelope" type="envType" minOccurs="1" xdb:SQLName="ENVELOPE"/>
    62      </xs:sequence>
    63    </xs:complexType>
    64    <xs:complexType name="layerType">
    65      <xs:sequence>
    66        <xs:element name="layername"  type="nameType" minOccurs="1" xdb:SQLName="LAYERNAME" />
    67        <xs:element name="layerid"  type="nameType" minOccurs="1" xdb:SQLName="LAYERID" />
    68        <xs:element name="service" type="nameType" minOccurs="1" xdb:SQLName="SERVICE"/>
    69        <xs:element name="visible" type="boolType" xdb:SQLName="VISIBLE"/>
    70        <xs:element name="ftype" type="nameType" xdb:SQLName="FTYPE" minOccurs="1" maxOccurs="1"/>
    71      </xs:sequence>
    72    </xs:complexType>
    73     <xs:complexType name="mapType">
    74      <xs:sequence>
    75        <xs:element name="mapname"  type="nameType" minOccurs="1" xdb:SQLName="MAPNAME"/>
    76        <xs:element name="layer"  type="layerType" minOccurs="1" maxOccurs="unbounded" xdb:SQLName="LAYER" />
    77        <xs:element name="placemark" type="placemarkType" minOccurs="1" maxOccurs="unbounded"  xdb:SQLName="PLACEMARK"/>
    78      </xs:sequence>
    79    </xs:complexType>
    80    <xs:complexType name="mapsetType" xdb:SQLType="mapset_t">
    81      <xs:sequence>
    82        <xs:element name="username"  type="usernameType" minOccurs="1" xdb:SQLName="USERNAME" />
    83       <xs:element name="map" type="mapType" minOccurs="1" maxOccurs="unbounded"  xdb:SQLName="MAP" xdb:SQLCollType="MAP_V"/>
    84       <xs:element name="startmap" type="nameType" minOccurs="1" maxOccurs="1" xdb:SQLName="STARTMAP"/>
    85       <xs:element name="startplace" type="nameType" minOccurs="1" maxOccurs="1" xdb:SQLName="STARTPLACE"/>
    86      </xs:sequence>
    87    </xs:complexType>
    88   <!--definition of main element -->
    89    <xs:element name="mapset" type="mapsetType" xdb:defaultTable="MAPSETXML">
    90      <xs:unique name="mapNameKey">
    91         <xs:selector xpath=".//map"/>
    92         <xs:field xpath="mapname"/>
    93      </xs:unique>
    94    </xs:element>
    95    </xs:schema>');
    96  begin
    97    if (dbms_xdb.existsResource(:schemaPath)) then
    98      dbms_xdb.deleteResource(:schemaPath);
    99    end if;
    100    res := dbms_xdb.createResource(:schemaPath,xmlSchema);
    101  end;
    102  /
    PL/SQL procedure successfully completed.
    SQL> begin
      2    dbms_xmlschema.registerSchema
      3    (
      4      :schemaURL,
      5      xdbURIType(:schemaPath).getClob(),
      6      TRUE,TRUE,FALSE,TRUE
      7    );
      8  end;
      9  /
    PL/SQL procedure successfully completed.
    SQL> declare
      2    nested_table_name varchar2(32);
      3  begin
      4    select table_name
      5      into nested_table_name
      6      from user_nested_tables
      7     where table_type_name = 'MAP_V'
      8       and parent_table_name = 'MAPSETXML';
      9
    10     execute immediate 'rename "'|| nested_table_name ||'" to MAP_TABLE';
    11
    12  end;
    13  /
    PL/SQL procedure successfully completed.
    SQL> desc MAPSETXML
    Name                                      Null?    Type
    TABLE of SYS.XMLTYPE(XMLSchema "http://localhost:8080/public/mapset.xsd" Element "mapset") STORAGE Object-relational TYPE "mapset_t"
    SQL> --
    SQL> desc MAP_TABLE
    Name                                      Null?    Type
    SYS_XDBPD$                                         XDB.XDB$RAW_LIST_T
    MAPNAME                                            VARCHAR2(50 CHAR)
    LAYER                                              LAYER7525_COLL
    PLACEMARK                                          PLACEMARK7528_COLL
    SQL> --
    SQL> --
    SQL> create or replace trigger VALIDATE_MAPSET
      2  before insert or update on MAPSETXML
      3  for each row
      4  begin
      5     :new.object_value.schemaValidate();
      6  end;
      7  /
    Trigger created.
    SQL> insert into MAPSETXML values ( xmltype('<mapset>
      2  <username>tester1</username>
      3  <map>
      4  <mapname>Florida</mapname>
      5  <layer>
      6  <layername>Counties</layername>
      7  <layerid>counties</layerid>
      8  <service>base</service>
      9  <visible>1</visible>
    10  <ftype>polygon</ftype>
    11  </layer>
    12  <placemark>
    13  <placename>Florida</placename>
    14  <envelope>
    15  <minx>-186185.234572</minx>
    16  <miny>2709914.999735</miny>
    17  <maxx>596332.812876</maxx>
    18  <maxy>3464678.999670</maxy>
    19  </envelope>
    20  </placemark>
    21  </map>
    22  <startmap>test</startmap>
    23  <startplace>Tallahassee</startplace>
    24  </mapset>
    25  ').createSchemaBasedXML('http://localhost:8080/public/mapset.xsd'))
    26  /
    1 row created.
    SQL> commit
      2  /
    Commit complete.
    SQL> set long 100000
    SQL> --
    SQL> select * from MAPSETXML
      2  /
    SYS_NC_ROWINFO$
    <mapset>
      <username>tester1</username>
      <map>
        <mapname>Florida</mapname>
        <layer>
          <layername>Counties</layername>
          <layerid>counties</layerid>
          <service>base</service>
          <visible>1</visible>
          <ftype>polygon</ftype>
        </layer>
    SYS_NC_ROWINFO$
        <placemark>
          <placename>Florida</placename>
          <envelope>
            <minx>-186185.234572</minx>
            <miny>2709914.999735</miny>
            <maxx>596332.812876</maxx>
            <maxy>3464678.999670</maxy>
          </envelope>
        </placemark>
      </map>
      <startmap>test</startmap>
    SYS_NC_ROWINFO$
      <startplace>Tallahassee</startplace>
    </mapset>
    SQL> CREATE OR REPLACE FUNCTION getMaps(userName varchar2)
      2  RETURN XMLTYPE
      3  AS
      4  xmlDoc XMLTYPE;
      5  BEGIN
      6    SELECT extract(OBJECT_VALUE, '/mapset/map') into xmlDoc
      7    FROM mapsetxml
      8    WHERE existsNode(OBJECT_VALUE,'/mapset['''|| username ||''']')=1;
      9    RETURN xmlDoc;
    10  END;
    11  /
    Function created.
    SQL> select getMaps('Florida') from dual;
    GETMAPS('FLORIDA')
    <map>
      <mapname>Florida</mapname>
      <layer>
        <layername>Counties</layername>
        <layerid>counties</layerid>
        <service>base</service>
        <visible>1</visible>
        <ftype>polygon</ftype>
      </layer>
      <placemark>
        <placename>Florida</placename>
    GETMAPS('FLORIDA')
        <envelope>
          <minx>-186185.234572</minx>
          <miny>2709914.999735</miny>
          <maxx>596332.812876</maxx>
          <maxy>3464678.999670</maxy>
        </envelope>
      </placemark>
    </map>
    SQL>The following Java code
    package com.oracle.st.xmldb.otn;
    import com.oracle.st.xmldb.pm.common.baseApp.BaseApplication;
    import com.oracle.st.xmldb.pm.examples.GetResourceByResourceID;
    import oracle.jdbc.OracleCallableStatement;
    import oracle.jdbc.OracleTypes;
    import oracle.sql.RAW;
    import oracle.xdb.XMLType;
    import oracle.xdb.dom.XDBDocument;
    public class T415572 extends BaseApplication {
        public T415572() {
        public void doSomething(String[] Args) throws Exception
          OracleCallableStatement  statement = null;
          boolean result;
          statement = (OracleCallableStatement) getConnection().prepareCall("{ ? = call getmaps(?)}");
          statement.registerOutParameter(1,OracleTypes.OPAQUE,"SYS.XMLTYPE");
          statement.setString(2,"Florida");
          result = statement.execute();
          XMLType xml = (XMLType) statement.getObject(1);
          statement.close();
          XDBDocument doc = (XDBDocument) xml.getDOM();
          doc.writeToOutputStream(System.out);
          doc.close();
          getConnection().close();
        public static void main (String[] args)
         try
           BaseApplication example = new T415572();
           example.initializeConnection();
           example.doSomething(args);
         catch (Exception e)
           e.printStackTrace();
    }results in
    C:\TEMP>
    C:\Oracle\JDeveloper\jdk\bin\javaw.exe -client -classpath C:\xdb\JDeveloper\Classes;C:\Oracle\product\10.2.0\db_1\jdbc\lib\ojdbc14.jar;C:\Oracle\product\10.2.0\db_1\LIB\xmlparserv2.jar;C:\Oracle\product\10.2.0\db_1\RDBMS\jlib\xdb.jar;C:\xdb\JDeveloper\jakarta-slide-webdavclient-bin-2.1\lib\jakarta-slide-webdavlib-2.1.jar;C:\xdb\JDeveloper\jakarta-slide-webdavclient-bin-2.1\lib\commons-httpclient.jar;C:\xdb\JDeveloper\jakarta-slide-webdavclient-bin-2.1\lib\commons-logging.jar;C:\xdb\JDeveloper\jakarta-slide-webdavclient-bin-2.1\lib\jdom-1.0.jar -Dcom.oracle.st.xmldb.pm.ConnectionParameters=C:\\xdb\\jdeveloper\\SimpleExamples\\LocalConnection.xml -Dhttp.proxyHost=www-proxy.us.oracle.com -Dhttp.proxyPort=80 -Dhttp.nonProxyHosts=192.168.0.77|localhost|192.168.1.1|*.oracle.com|*.us.oracle.com -Dhttps.proxyHost=www-proxy.us.oracle.com -Dhttps.proxyPort=80 -Dhttps.nonProxyHosts=192.168.0.77|localhost|192.168.1.1|*.oracle.com|*.us.oracle.com com.oracle.st.xmldb.otn.T415572 -mx2048M
    ConnectionProvider.establishConnection(): Connecting as SCOTT/TIGER@jdbc:oracle:oci8:@(description=(address=(host=localhost)(protocol=tcp)(port=1521))(connect_data=(service_name=ORA10GR2.xp.mark.drake.oracle.com)(server=DEDICATED)))
    ConnectionProvider.establishConnection(): Database Connection Established
    <map>
      <mapname>Florida</mapname>
      <layer>
        <layername>Counties</layername>
        <layerid>counties</layerid>
        <service>base</service>
        <visible>1</visible>
        <ftype>polygon</ftype>
      </layer>
      <placemark>
        <placename>Florida</placename>
        <envelope>
          <minx>-186185.234572</minx>
          <miny>2709914.999735</miny>
          <maxx>596332.812876</maxx>
          <maxy>3464678.999670</maxy>
        </envelope>
      </placemark>
    </map>
    Process exited with exit code 0.The code also works fine when modified to work with the thin driver...
    Message was edited by:
    mdrake

  • Return rowset to JSP Page

    In producing a report table, for example, I'd like to have the JSP page access the
    rowset from the Bean and then walk through the rowset a row at a time, formatting
    output. All the examples I've found create the table code in the servlet. I'd like to
    avoid that, creating the html in the JSP page only.

    hi,
    I think You can do it in this way.
    Store the values that you get from rowset in a hash table and set the return type of your bean method to hashtable. When you call the method in jsp assign the return value to a hash table. From there you can manipulate the objects in hash table.
    Hope this works,
    chandu

Maybe you are looking for

  • HT204053 How do I use my apple ID for U.S. and Emirati stores?

    How do I use the same Apple ID in different stores?

  • Sale Order # - MRP element missing in MD04

    Hi, I created an SO with a material, for which planning was not done in MRP view. Later I changed the schedule line category from CN to CP in VA02. Then MRP run is carried out for that particular plant (1001) . IN MD04, i could able to get the detail

  • Graphics drivers for e550 on Ubuntu

    I recently purchased an e550 - 8gb ram and the hybrid Intel/radeon graphics set - up.  I've installed Ubuntu 14.04 in a dual boot setup.  Occasionally I am seeing missing characters in text field so I believe I need to tweak it replace the auto insta

  • Quick Time Pro for Windows

    I've got a digital camera which uses Quick Time (for Windows) to play back 'movies' I've recorded on it. If I upgrade to Quick Time Pro for Windows will I be able to convert and export the Quick Time files to a format that my DVD players can recogniz

  • ACE-4710 : XML Syntax Error du to a missing closing tag

    Hi, We use XML over HTTPS to gather connections information from a management station. We can successfully read the number of connections per real server (rserver), but the ACE returns a buggy XML code when we tray to get the number of connections th