Statement.close() Not closing the Result set

Hi all,
I have the following code which invokes a procedure in Oracle database
public static callProcedure(Connection connection,String procedure){
ResultSet resultSet = null;
CallableStatement callableStatement = null;
try {
callableStatement = connection.prepareCall(procedure);
callableStatement.registerOutParameter(1,OracleTypes.CURSOR);
callableStatement.execute();
resultSet =((OracleCallableStatement)callableStatement).getCursor(1);
} catch (Exception exception) {
exception.printStackTrace();
} finally {
try {
callableStatement.close();
} catch (SQLException sqlException) {
sqlException.printStackTrace()
return resultSet;
Ideally if i try to iterate through the result set which is returned then it should give me resultset closed as i am closing the resultset. But this is not happening.
Please anybody can explain the isue

Hi,
That is not easy to explain, I might take a guess and say that a statement cache is being used therefore the statement is not actually being closed.
I always close the reultset then the statement so wouldn't notice this behaviour.
Why are you returning a resultset anyway? If you really need to do this I would suggest using a disconnected resultset:
OracleCachedRowSet ocrs = new OracleCachedRowSet();
ocrs.populate(resultSet);
return ocrs;

Similar Messages

  • The statement did not return a result set in ireport

    Hi,
        I am Building a Report in iReport(Jasper Reports). I called a stored procedure from iReport by passing a parameter in Query Editor. I am getting an exception saying "The statement did not return a result set". When
    i use Temp Tables in stored procedure i am getting the exception.
    If there is no temptable in Stored procedure there wont be any exception.
    This is my Stored procedure
    Create PROCEDURE [XUSP_REPORT_SOPRINT] @BNUM VARCHAR(20) AS
    BEGIN
    DECLARE @FQTY BIGINT
    DECLARE @ITNAME VARCHAR(100)
    DECLARE @COUNT INT=0
    DECLARE @COUNT1 INT=0
    CREATE TABLE #BILL_PRINT(
        [BNUM] [varchar](20) NOT NULL,
        [CNAME] [varchar](30) NOT NULL,
        [CNUM] [int] NOT NULL,
        [ITNAME] [varchar](100) NOT NULL,
        [ITEM#] [int] NOT NULL,
        [QTY] [int] NOT NULL DEFAULT 0,
        [UNIT] [varchar](5) NOT NULL,
        [PRICE] [float] NOT NULL DEFAULT 0,
        [BASIC] [float] NOT NULL DEFAULT 0,
        [DISCOUNT] [float] NOT NULL DEFAULT 0,
        [FRQTY] [int] NOT NULL DEFAULT 0,
        [BADDR] [varchar](300) NULL,
        [CADDR] [varchar](300) NOT NULL,
        [BDATE] [datetime] NULL DEFAULT (sysdatetime()),
        [BILLBY] [varchar](50) NOT NULL,
        [ROUTE] [varchar](200) NULL,
        [AMT] [float] NOT NULL DEFAULT 0,
        [VAT] [float] NOT NULL DEFAULT 0,
        [VAT AMT] [float] NOT NULL DEFAULT 0,
        [AMT_AF_DISC] [float] NOT NULL DEFAULT 0,
        [AMT_AF_VAT] [float] NOT NULL DEFAULT 0,
        [TOT_DISC] [float] NOT NULL DEFAULT 0,
        [ROUND_OFF] [float] NOT NULL DEFAULT 0,
        [TOT_VAT] [float] NOT NULL DEFAULT 0,
        [AMT_UNDER_VAT] [float] NOT NULL DEFAULT 0,
        [NETT] [float] NOT NULL DEFAULT 0,
        [TOS] [varchar](30) NULL DEFAULT 0,
        [CDISC] [float] NOT NULL DEFAULT 0,
        [SDISC] [float] NOT NULL DEFAULT 0
    insert into #BILL_PRINT SELECT [BNUM]
          ,[CNAME]
          ,[CNUM]
          ,[ITNAME]
          ,[ITEM#]
          ,[QTY]
          ,[UNIT]
          ,[PRICE]
          ,[BASIC]
          ,[DISCOUNT]
          ,[FRQTY]
          ,[BADDR]
          ,[CADDR]
          ,[BDATE]
          ,[BILLBY]
          ,[ROUTE]
          ,[AMT]
          ,[VAT]
          ,[VAT AMT]
          ,[AMT_AF_DISC]
          ,[AMT_AF_VAT]
          ,[TOT_DISC]
          ,[ROUND_OFF]
          ,[TOT_VAT]
          ,[AMT_UNDER_VAT]
          ,[NETT]
          ,[TOS]
          ,[CDISC]
          ,[SDISC]
      FROM [SALES_DETAILS] WHERE BNUM=@BNUM
    CREATE TABLE #ITNAME_0
    ITEM VARCHAR(100) NOT NULL,
    FREE BIGINT NOT NULL
    INSERT INTO #ITNAME_0 SELECT ITNAME,FRQTY FROM SALES_DETAILS WHERE FRQTY<>0 AND BNUM=@BNUM
    --SELECT * FROM #ITNAME_0
    SET @COUNT=(SELECT COUNT(*) FROM #ITNAME_0)
    WHILE @COUNT!=0
    BEGIN
    SET @FQTY=(SELECT TOP(1) FREE FROM #ITNAME_0)
    SET @ITNAME=(SELECT TOP(1) ITEM FROM #ITNAME_0)
    SET @COUNT1=(SELECT COUNT(*) FROM #BILL_PRINT WHERE ITNAME=@ITNAME AND BNUM=@BNUM)
    IF @COUNT1=2
    BEGIN
        UPDATE #BILL_PRINT
        SET FRQTY+=@FQTY
        WHERE ITNAME=@ITNAME AND QTY<>0
        DELETE FROM #ITNAME_0 WHERE ITEM=@ITNAME AND FREE=@FQTY
        DELETE FROM #BILL_PRINT WHERE  ITNAME=@ITNAME AND QTY=0
    END
    SET @COUNT=@COUNT-1
    END
    --SELECT *FROM sales_details
    SELECT *FROM #BILL_PRINT where bnum=@bnum
    DROP TABLE #BILL_PRINT
    DROP TABLE #ITNAME_0
    END
    Please help me out in this.
    Thanks,
    Shreyas M

    This is a forum for Reporting Services (SSRS). If you're using Jasper reports then you should be posting in relevenat forums. I'm not sure there would be enough people with Jasper report experience here to help you out!
    Anyways in SSRS when  we use Temp tables in procedure it will throw exception in editor but when you save and run it will still work fine. Did you try saving it and executing report? Did the error still persisted?
    Please Mark This As Answer if it solved your issue
    Please Vote This As Helpful if it helps to solve your issue
    Visakh
    My MSDN Page
    My Personal Blog
    My Facebook Page

  • Avoid JDBC sender error: Execute statement did not return a result set

    Hi!
    My JDBC sender adapter towards MS SQL server works fine, with an Execute statement calling a stored procedure that returns the source data needed. The stored procedure itself updates the status of database table records, so that only the unread records are returned each time the stored procedure is called.
    However, the communication channel monitoring sets a red flag for the JDBC sender adapter, when there are no values to fetch from the database table (using the stored procedure). Message says: "Database-level error reported by JDBC driver while executing statement 'EXECUTE FetchMessage 1, 9000'. The JDBC driver returned the following error message: 'com.microsoft.sqlserver.jdbc.SQLServerException: The statement did not return a result set.'. For details, contact your database server vendor."
    This is not an error situation, as I do not expect there to be any values to fetch from the database at all times.
    I do not see how to change the stored procedure to avoid this error.
    Is there a parameter to be set on the JDBC adapter that I can use, so the red flag is avoided?
    Thanks for any input!
    Regards,
    Oeystein Emhjellen

    Hi Oeystein Emhjellen.
    The problem is Store Procedure that has to generate always a ResultSet (or cursor). If it doesn't have a output, you have to generate an Empty ResultSet.
    Like a SELECT Statement:
    If there are data, SELECT get an output result but if it get nothing the SELECT Statement get a empty ResultSet.
    Ask to your database team.
    I hope it helps you.
    Bruno.

  • OBIEE Answers does not display the result set of a report query

    Hi,
    We have a pivot table type of report in Oracle Business Intelligence Enterprise Edition v.10.1.3.3.2 Answers that has the following characteristics:
         3 Pages
         3 Sections , 4 Columns
         18363 Rows in the result set
    As per the NQQuery.log, the query for this report executes successfully resulting in 18363 rows. However, nothing comes up in the display on Answers. Moreover, no error is reported. The instanceconfig.xml file has the following setting:
    <PivotView>
         <CubeMaxRecords>30000</CubeMaxRecords>
         <CubeMaxPopulatedCells>300000</CubeMaxPopulatedCells>
    </PivotView>
    Even with these settings, Answers just returns a blank page - nothing is displayed in the name of the result set of the report query. Has anyone encountered this problem scenario before?
    Any help is much appreciated.
    Thanks,
    Piyush

    Hi Fiston / Pradeep,
    Thanks for your inputs. A few points to note:
    -> I am actually not getting any error message in answers or the NQQuery log. Moreover I am not getting any errors related to "query governor limit exceeding in cube generation" also.
    -> I have other pivot table type of reports in the same repository that work fine. In fact the report which has this issue even works sometimes - what actually is happening is that if I alter the number of sections from 3 to 4, then the result set changes from 14755 Rows to 18363 Rows and as per the NQQuery.log in both cases the query completes successfully. However, when the result set has 14755 rows, I get to see the output in Answers; however when the result set is 18636 rows, the Answers screen just goes blank and does not show any output or error. This makes me believe that there is some parameter in instanceconfig or the NQSconfig file - I have tried a lot of changes but nothing works !
    Any help is much appreciated.
    Best Regards,
    Piyush

  • Why to need close the result set and statement

    why to need close the result set and statement

    It's best to explicitly close every ResultSet, Statement, and Connection in the narrowest scope possible.
    These should be closed in a finally block.
    Since each close() method throws SQLException, each one should be in an individual try/catch block to ensure that a failure to close one won't ruin the chances for all the others.
    You can capture this in one nice utility class, like this:
    package db;
    import java.sql.*;
    import java.util.ArrayList;
    import java.util.Map;
    import java.util.LinkedHashMap;
    import java.util.List;
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    * Created by IntelliJ IDEA.
    * User: MD87020
    * Date: Feb 16, 2005
    * Time: 8:42:19 PM
    * To change this template use File | Settings | File Templates.
    public class DatabaseUtils
         * Logger for DatabaseUtils
        private static final Log logger = LogFactory.getLog(DatabaseUtils.class);
        /** Private default ctor to prevent subclassing and instantiation */
        private DatabaseUtils() {}
         * Close a connection
         * @param connection to close
        public static void close(Connection connection)
            try
                if ((connection != null) && !connection.isClosed())
                    connection.close();
            catch (SQLException e)
                logger.error("Could not close connection", e);
         * Close a statement
         * @param statement to close
        public static void close(Statement statement)
            try
                if (statement != null)
                    statement.close();
            catch (SQLException e)
                logger.error("Could not close statement", e);
         * Close a result set
         * @param rs to close
        public static void close(ResultSet rs)
            try
                if (rs != null)
                    rs.close();
            catch (SQLException e)
                logger.error("Could not close result set", e);
         * Close both a connection and statement
         * @param connection to close
         * @param statement to close
        public static void close(Connection connection, Statement statement)
            close(statement);
            close(connection);
         * Close a connection, statement, and result set
         * @param connection to close
         * @param statement to close
         * @param rs to close
        public static void close(Connection connection,
                                 Statement statement,
                                 ResultSet rs)
            close(rs);
            close(statement);
            close(connection);
         * Helper method that maps a ResultSet into a map of columns
         * @param rs ResultSet
         * @return map of lists, one per column, with column name as the key
         * @throws SQLException if the connection fails
        public static final Map toMap(ResultSet rs) throws SQLException
            List wantedColumnNames = getColumnNames(rs);
            return toMap(rs, wantedColumnNames);
         * Helper method that maps a ResultSet into a map of column lists
         * @param rs ResultSet
         * @param wantedColumnNames of columns names to include in the result map
         * @return map of lists, one per column, with column name as the key
         * @throws SQLException if the connection fails
        public static final Map toMap(ResultSet rs, List wantedColumnNames)
            throws SQLException
            // Set up the map of columns
            int numWantedColumns    = wantedColumnNames.size();
            Map columns             = new LinkedHashMap(numWantedColumns);
            for (int i = 0; i < numWantedColumns; ++i)
                List columnValues   = new ArrayList();
                columns.put(wantedColumnNames.get(i), columnValues);
            while (rs.next())
                for (int i = 0; i < numWantedColumns; ++i)
                    String columnName   = (String)wantedColumnNames.get(i);
                    Object value        = rs.getObject(columnName);
                    List columnValues   = (List)columns.get(columnName);
                    columnValues.add(value);
                    columns.put(columnName, columnValues);
            return columns;
         * Helper method that converts a ResultSet into a list of maps, one per row
         * @param rs ResultSet
         * @return list of maps, one per row, with column name as the key
         * @throws SQLException if the connection fails
        public static final List toList(ResultSet rs) throws SQLException
            List wantedColumnNames  = getColumnNames(rs);
            return toList(rs, wantedColumnNames);
         * Helper method that maps a ResultSet into a list of maps, one per row
         * @param rs ResultSet
         * @param wantedColumnNames of columns names to include in the result map
         * @return list of maps, one per column row, with column names as keys
         * @throws SQLException if the connection fails
        public static final List toList(ResultSet rs, List wantedColumnNames)
            throws SQLException
            List rows = new ArrayList();
            int numWantedColumns = wantedColumnNames.size();
            while (rs.next())
                Map row = new LinkedHashMap();
                for (int i = 0; i < numWantedColumns; ++i)
                    String columnName   = (String)wantedColumnNames.get(i);
                    Object value = rs.getObject(columnName);
                    row.put(columnName, value);
                rows.add(row);
            return rows;
          * Return all column names as a list of strings
          * @param rs query result set
          * @return list of column name strings
          * @throws SQLException if the query fails
        public static final List getColumnNames(ResultSet rs) throws SQLException
            ResultSetMetaData meta  = rs.getMetaData();
            int numColumns = meta.getColumnCount();
            List columnNames = new ArrayList(numColumns);
            for (int i = 1; i <= numColumns; ++i)
                columnNames.add(meta.getColumnName(i));
            return columnNames;
    }Anybody who lets the GC or timeouts or sheer luck handle their resource recovery for them is a hack and gets what they deserve.
    Do a search on problems with Oracle cursors being exhausted and learn what the root cause is. That should convince you.
    scsi-boy is 100% correct.
    %

  • Gor The result set is closed after switch to latest microsoft JDBC driver

    The same code works fine with the previous version of the microsoft JDBC driver, but throws
    com.microsoft.sqlserver.jdbc.SQLServerException: The result set is closed.
    for the JDBC driver 4.
    Please Help!
    Thanks.

    I found the same exception when dealing with ResultSetMetaData.
    Using the old driver (1.2.2828.100) it was possible to do something like:
    Statement s = con.createStatement();
    ResultSet r = s.executeQuery("select * from <table>");
    ResultSetMetaData m = r.getMetaData();
    r.close();
    s.close();
    int numCols = m.getColumnCount();
    But using the new driver (2.0.1803.100) it complains that the result set is closed.
    The solution was to keep the ResultSet and Statement open until after the ResultSetMetaData is no longer needed. It is somewhat inconvenient because before it was possible to have a utility method that would return a ResultSetMetaData object and not have to worry about keeping the Statement and ResultSet objects around.
    I was hoping for a speed increase for batch inserts by having the latest driver, sadly there is no performance gain.

  • How to add a dummy row in the result set of a SELECT statement.

    Hello Everyone -
    I have requirment to add a dummy row in the result set of a SELECT statement.
    For e.g. lets say there is a table Payment having following colums:
    Payment_id number
    status varchar2(10)
    amount number
    payment_date date
    so here is the data :-
    Payment_id Status Amount payment_date
    1 Applied 100 12/07/2008
    2 Reversed 200 01/ 06/2009
    3 Applied 300 01/ 07/2009
    Here is my SQL
    Select * form payment where payment_date >= 01/01/2009
    Output will be
    2 Reversed 200 01/ 06/2009
    3 Applied 300 01/ 07/2009
    My desired output is below
    2 Reversed 200 01/ 06/2009
    3 Applied 300 01/ 07/2009
    2 Reversed -200 01/ 06/2009 ------(Dummy Row)
    Thrid row here is the dummy row which I want to add when status is "Reversed"
    I would be very thankful for any kind of help in this regard ...
    Thanks,
    Gaurav

    Cartesion joining against a dummy table is a useful method of creating a dummy row:
    with my_tab as (select 1 cust_id, 1 Payment_id, 'Applied' Status, 100 Amount, to_date('12/07/2008', 'mm/dd/yyyy') payment_date from dual union all
                    select 1 cust_id, 2 Payment_id, 'Reversed' Status, 200 Amount, to_date('01/06/2009', 'mm/dd/yyyy') payment_date from dual union all
                    select 1 cust_id, 3 Payment_id, 'Applied' Status, 300 Amount, to_date('01/06/2009', 'mm/dd/yyyy') payment_date from dual union all
                    select 2 cust_id, 1 Payment_id, 'Applied' Status, 100 Amount, to_date('12/07/2008', 'mm/dd/yyyy') payment_date from dual union all
                    select 2 cust_id, 2 Payment_id, 'Reversed' Status, 200 Amount, to_date('01/05/2009', 'mm/dd/yyyy') payment_date from dual union all
                    select 2 cust_id, 3 Payment_id, 'Applied' Status, 300 Amount, to_date('01/06/2009', 'mm/dd/yyyy') payment_date from dual union all
                    select 2 cust_id, 4 Payment_id, 'Reversed' Status, -400 Amount, to_date('01/06/2009', 'mm/dd/yyyy') payment_date from dual union all
                    select 2 cust_id, 5 Payment_id, 'Applied' Status, 500 Amount, to_date('01/07/2009', 'mm/dd/yyyy') payment_date from dual),
                    --- end of mimicking your table
          dummy as (select 'Reversed' col1, 1 rn from dual union all
                    select 'Reversed' col1, 2 rn from dual)
    select mt.cust_id,
           mt.payment_id,
           mt.status,
           decode(dummy.rn, 2, -1*mt.amount, mt.amount) amount,
           mt.payment_date
    from   my_tab mt,
           dummy
    where  mt.status = dummy.col1 (+)
    order by mt.cust_id, mt.payment_id, dummy.rn nulls first;
    CUST_ID     PAYMENT_ID     STATUS     AMOUNT     PAYMENT_DATE
    1     1     Applied     100     07/12/2008
    1     2     Reversed     200     06/01/2009
    1     2     Reversed     -200     06/01/2009
    1     3     Applied     300     06/01/2009
    2     1     Applied     100     07/12/2008
    2     2     Reversed     200     05/01/2009
    2     2     Reversed     -200     05/01/2009
    2     3     Applied     300     06/01/2009
    2     4     Reversed     -400     06/01/2009
    2     4     Reversed     400     06/01/2009
    2     5     Applied     500     07/01/2009Edited by: Boneist on 07-Jan-2009 23:10
    NB. You may have to mess around with the ordering if that's not come back in the order you wanted. You didn't mention what the rules were for any expected ordering though, so I've made up my own *{;-)
    Also, I added an identifier (cust_id) to differentiate between different sets of payments, since that's usually the case. Remove that if it's not applicable for your case.

  • The operation is not allowed for result set type FORWARD_ONLY

    Hi,
    I am trying to use scroll insensitive resultset in following manner-
    Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
    ResultSet rs = stmt.executeQuery("some sql here");
    rs.last();
    but the rs.last() throws this exception-
    com.sap.dbtech.jdbc.exceptions.SQLExceptionSapDB: The operation is not allowed for result set type FORWARD_ONLY.
         at com.sap.dbtech.jdbc.ResultSetSapDB.assertNotForwardOnly(ResultSetSapDB.java:2725)
         at com.sap.dbtech.jdbc.ResultSetSapDB.last(ResultSetSapDB.java:557)
    Database version: Kernel    7.5.0    Build 019-121-082-363
    Driver Version: MaxDB JDBC Driver, MySQL MaxDB, 7.6.0    Build 030-000-005-567
    This used to work with 7.5 version driver. Why this is failing with 7.6 driver, any clues?
    Thanks,
    Vinod

    Hi Vinod,
    due to performance improvement when using forward only cursor we changed the default for the resultset type from TYPE_SCROLL_SENSITIVE to TYPE_FORWARD_ONLY starting with JDBC driver version 7.6. So I guess the exception comes from a statement where you didn't set the resultset type while creating it. Please check if all of the statements that you want to be scrollable have set the correct resultset type.
    Regards,
    Marco

  • How to return the result set of multiple select statements as one result set?

    Hi All,
    I have multiple select statements in my stored procedure that I want to return as one result set 
    for instance 
    select id from tableA
    union 
    select name from table b 
    but union will not work because the result sets datatypes are not identical so how to go about this ?
    Thanks

    You have to CAST or CONVERT (or implicitly convert) the columns to the same datatype.  You must find a datatype that both columns can be converted to without error.  In your example I'm guessing id is an int and name is a varchar or nvarchar. 
    Since you didn't convert the datatypes, SQL will use its data precedence rules and attempt to convert name to an int.  If any row contains a row that has a value in name that cannot be converted to an int, you will get an error.  The solution is
    to force SQL to convert the int to varchar.  So you want something like
    select cast(id as varchar(12)) from tableA
    union
    select name from tableb
    If the datatypes are something other that int or varchar, you must find a compatable datatype and then convert one (or both) of the columns to that datatype.
    Tom

  • RIDC api: The result set 'content' was not found or is empty

    Hi,
    I am trying to add a revision using COLLECTION_CHECKIN_REVISION. The content which I want to add a revision has only one revision i.e. 1,
    and its dID is 3746 and is already checked out.
    <code>
         binder.putLocal ("IdcService", "COLLECTION_CHECKIN_REVISION");
         // get the binder
         binder.putLocal ("dDocTitle", "Html file");
         binder.putLocal ("dDocName", "SUN00100");
         binder.putLocal ("dDocType", "Document");
         binder.putLocal ("dSecurityGroup", "Public");
         binder.putLocal("hasCollectionID", "true");
         binder.putLocal("dID", "3746");
         binder.putLocal("dRevLabel", "2");
         binder.putLocal("dCollectionID", this.getFolderIdFromPath(idcClient, userContext, PATH));
         System.out.println("dCollectionID###############################" +binder.getLocal("dCollectionID"));
         binder.addFile ("primaryFile", new TransferFile(new File("D:\\P6WS\\RIDC Test\\src\\com\\oracle\\ridc\\poc\\2.html")));
         // checkin the file
         response = idcClient.sendRequest(userContext, binder);
         System.out.println("response "+response.getResponseAsString());
    </code>
    And the output is as follows
    dCollectionID###############################739373434448003784
    response <?hda version="11gR1-11.1.1.5.0-idcprod1-110413T184243" jcharset=UTF-8 encoding=UTF-8?>
    @Properties LocalData
    deleteCompleteInCollections=true
    dDocType=Document
    refreshSubMonikers=
    dUser=sysadmin
    anyState=true
    primaryFile=2.html
    StatusMessage=<strong>The result set 'content' was not found or is empty.</strong>
    UserTimeZone=UTC
    localizedForResponse=1
    dDocName=SUN00100
    changedMonikers=
    I want to understand which content is being referred. The primaryFile is existing in the same location.
    Did I missed out any required parameter.
    regards,
    Sunil Kumar Dhage
    Edited by: 881595 on Aug 26, 2011 4:18 AM

    Like last time: documentation is not a big help here, so you have to do a bit of investigation yourself.
    In order to understand result sets, check this link: http://download.oracle.com/docs/cd/E17904_01/doc.1111/e10726/c04_master_usage.htm#CSIDO249
    ('content' is the name of the result set)
    I can't imagine why you would need such a result set while checkin in a new revision to a folder, but the documentation (http://download.oracle.com/docs/cd/E17904_01/doc.1111/e11011/c08_folders.htm#i1082329) advices that some sub services are called, so it might actually be an error coming from these subservices. I'd suggest to narrow down the search first - turn on requestaudit in server-wide tracing (see here: http://download.oracle.com/docs/cd/E17904_01/doc.1111/e10792/c02_processes.htm#CSMSP536).
    Alternatively, you could also perform your service call from GUI and trace what parameters are provided. I guess something will be missing.

  • JSP Servlet and convert the result set of an SQL Query To XML file

    Hi all
    I have a problem to export my SQL query is resulty into an XML file I had fixed my servlet and JSP so that i can display all the records into my database and that the goal .Now I want to get the result set into JSP so that i can create an XML file from that result set from the jsp code.
    thisis my servlet which will call the jsp page and the jsp just behind it.
    //this is the servlet
    import java.io.*;
    import java.lang.reflect.Array;
    import java.sql.*;
    import java.util.ArrayList;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.naming.*;
    import javax.sql.*;
    public *class *Campaign *extends *HttpServlet
    *private* *final* *static* Logger +log+ = Logger.+getLogger+(Campaign.*class*.getName());
    *private* *final* *static* String +DATASOURCE_NAME+ = "jdbc/SampleDB";
    *private* DataSource _dataSource;
    *public* *void* setDataSource(DataSource dataSource)
    _dataSource = dataSource;
    *public* DataSource getDataSource()
    *return* _dataSource;
    *public* *void* init()
    *throws* ServletException
    *if* (_dataSource == *null*) {
    *try* {
    Context env = (Context) *new* InitialContext().lookup("java:comp/env");
    _dataSource = (DataSource) env.lookup(+DATASOURCE_NAME+);
    *if* (_dataSource == *null*)
    *throw* *new* ServletException("`" + +DATASOURCE_NAME+ + "' is an unknown DataSource");
    } *catch* (NamingException e) {
    *throw* *new* ServletException(e);
    protected *void *doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException
    Connection conn = *null*;
    *try* {
    conn = getDataSource().getConnection();
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("select post_id,comments,postname from app.posts");
    // out.println("Le r&eacute;sultat :<br>");
    ArrayList <String> Lescomments= *new* ArrayList<String>();
    ArrayList <String> Lesidentifiant = *new* ArrayList<String>();
    ArrayList <String> Lesnoms = *new* ArrayList <String>();
    *while* (rs.next()) {
    Lescomments.add(rs.getString("comments"));
    request.setAttribute("comments",Lescomments);
    Lesidentifiant.add(rs.getString("post_id"));
    request.setAttribute("id",Lesidentifiant);
    Lesnoms.add(rs.getString("postname"));
    request.setAttribute("nom",Lesnoms);
    rs.close();
    stmt.close();
    *catch* (SQLException e) {
    *finally* {
    *try* {
    *if* (conn != *null*)
    conn.close();
    *catch* (SQLException e) {
    // les param&egrave;tres sont corrects - on envoie la page r&eacute;ponse
    getServletContext().getRequestDispatcher("/Campaign.jsp").forward(request,response);
    }///end of servlet
    }///this is the jsp page called
    <%@ page import="java.util.ArrayList" %>
    <%
    // on r&eacute;cup&egrave;re les donn&eacute;es
    ArrayList nom=(ArrayList)request.getAttribute("nom");
    ArrayList id=(ArrayList)request.getAttribute("id");
    ArrayList comments=(ArrayList) request.getAttribute("comments");
    %>
    <html>
    <head>
    <title></title>
    </head>
    <body>
    Liste des campagnes here i will create the xml file the problem is to display all rows
    <hr>
    <table>
    <tr>
    </tr>
    <tr>
    <td>Comment</td>
    <td>
    <%
    for( int i=0;i<comments.size();i++){
    out.print("<li>" + (String) comments.get(i) + "</li>\n");
    }//for
    %>
    </tr>
    <tr>
    <td>nom</td>
    <td>
    <%
    for( int i=0;i<nom.size();i++){
    out.print("<li>" + (String) nom.get(i) + "</li>\n");
    }//for
    %>
    </tr>
    <tr>
    <td>id</td>
    <td>
    <%
    for( int i=0;i<id.size();i++){
    out.print("<li>" + (String) id.get(i) + "</li>\n");
    }//for
    %>
    </tr>
    </table>
    </body>
    </html>
    This is how i used to create an XML file in a JSP page only without JSP/SERVLET concept:
    <%@ page import="java.sql.*" %>
    <%@ page import="java.io.*" %>
    <%
    // Identify a carriage return character for each output line
    int iLf = 10;
    char cLf = (*char*)iLf;
    // Create a new empty binary file, which will content XML output
    File outputFile = *new* File("C:\\Users\\user\\workspace1\\demo\\WebContent\\YourFileName.xml");
    //outputFile.createNewFile();
    FileWriter outfile = *new* FileWriter(outputFile);
    // the header for XML file
    outfile.write("<?xml version='1.0' encoding='ISO-8859-1'?>"+cLf);
    try {
    // Define connection string and make a connection to database
    Connection conn = DriverManager.getConnection("jdbc:derby://localhost:1527/SAMPLE","app","app");
    Statement stat = conn.createStatement();
    // Create a recordset
    ResultSet rset = stat.executeQuery("Select * From posts");
    // Expecting at least one record
    *if*( !rset.next() ) {
    *throw* *new* IllegalArgumentException("No data found for the posts table");
    outfile.write("<Table>"+cLf);
    // Parse our recordset
    // Parse our recordset
    *while*(rset.next()) {
    outfile.write("<posts>"+cLf);
    outfile.write("<postname>" + rset.getString("postname") +"</postname>"+cLf);
    outfile.write("<comments>" + rset.getString("comments") +"</comments>"+cLf);
    outfile.write("</posts>"+cLf);
    outfile.write("</Table>"+cLf);
    // Everything must be closed
    rset.close();
    stat.close();
    conn.close();
    outfile.close();
    catch( Exception er ) {
    %>

    Please state your problem that you are having more clearly so we can help.
    I looked at your code I here are a few things you might consider:
    It looks like you are putting freely typed-in comments from end-users into an xml document.
    The problem with this is that the user may enter characters in his text that have special meaning
    to xml and will have to be escaped correctly. Some of these characters are less than character, greater than character and ampersand character.
    You may also have a similiar problem displaying them on your JSP page since there may be special characters that JSP has.
    You will have to read up on how to deal with these special characters (I dont remember what the rules are). I seem to recall
    if you use CDATA in your xml, you dont have to deal with those characters (I may be wrong).
    When you finish writing your code, test it by entering all keyboard characters to make sure they are processed, stored in the database,
    and re-displayed correctly.
    Also, it looks like you are putting business logic in your JSP page (creating an xml file).
    The JSP page is for displaying data ONLY and submitting back to a servlet. Put all your business logic in the servlet. Putting business logic in JSP is considered bad coding and will cause you many hours of headache trying to debug it. Also note: java scriptlets in a JSP page are only run when the JSP page is compiled into a servlet by java. It does not run after its compiled and therefore you cant call java functions after the JSP page is displayed to the client.

  • Virtual column in the result set of the query.

    Hi folks,
    I have table , let it be, EMP. It has columns ENAME,EMPNO,JOB etc.,
    My requirement is to add an extra column, not present in the table, having NULL value at the time of diplaying the results of a query. I hope you got it. So a column that does not exists in the table should get displayed in the resultant set when we query the results from that table. so my question is, how to write the SELECT statement using that virtual column.
    I'd thought of using X column in Dummy table but what if I don't have any dummy table in my particular schema.
    Please do revert back with the solution.
    Your effort'll be genuinely appreciated.
    Cheers
    PCZ

    Hi,
    If you just wany display null values you can write query like this :
    SELECT ENAME,EMPNO,JOB , NULL DUMMY_COLUMN FROM emp;
    Regrads
    Avinash

  • It is required to get the result set from the last query.

    I need this SP to return the result set from the last query.
    SET QUOTED_IDENTIFIER OFF
    GO
    SET ANSI_NULLS ON
    GO
    alter        proc spQ_GetASCBillingRateIDs2
    @ScheduleID CHAR(15),
    @startdate smalldatetime,
    @enddate smalldatetime
    as
    set nocount on
    truncate table tbltmpgroup
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tbltmptbltest]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[tbltmptbltest]
    exec sp_CreateTblTmpGroup
    insert into tbltmpgroup
    SELECT DISTINCT
    case when pd.billparent = 'N' then org.eligibleorgid
    else isnull(af.parentid, org.eligibleorgid) end as billorgid,
    pd.individualbill , pd.cobrabill, pd.billparent,
    org.eligibleorgid, org.polid, org.orgpolicyid,
    pp.planid,  pp.rateid,
    ps.ascinvoicedate,
    case when ps.ascclaimfromdate > @startdate then ps.ascclaimfromdate
    else @startdate end as premiumrundayFrom,
    case when ps.ascclaimtodate < @enddate then ps.ascclaimtodate
    else @enddate end as premiumrundayTo,
    fts.effdate, fts.termdate,
    case when fts.effdate > @startdate then fts.EffDate
    else @startdate end as ascStartDate,
    case when fts.termdate < @enddate then fts.termdate
    else @enddate end as ascEndDate
    FROM premiumschedule ps (nolock)
    inner join orgpolicy org (nolock)
    on org.ascinvoicerungroup between ps.premiumrundayfrom and ps.premiumrundayto
    inner join FundingTypeStatus fts
    on fts.orgpolicyid = org.orgpolicyid
    and fts.fundtype = 'ASC'
    and ((fts.effdate between @startdate and @enddate)
    or (fts.termdate between @startdate and @enddate)
    or (fts.effdate < @startdate and fts.termdate > @enddate))
    inner join eligibilityorg o (nolock)
    on org.eligibleorgid = o.eligibleorgid
    inner join policydef pd (nolock)
    on pd.polid = org.polid
    inner join policyplans pp (nolock)
    on pp.polid = org.polid
    inner join program p (nolock)
    on pd.programid = p.programid
    left join orgaffiliation af with (nolock)
    on org.eligibleorgid = af.childid
    WHERE ps.premiumscheduleid = @ScheduleID
    AND org.orgpolicyid <> ''
    go
    SELECT DISTINCT z.rateid, e.enrollid, z.ascstartdate, z.ascenddate
    into tbltmptbltest FROM enrollment E (nolock)
    inner join tbltmpgroup z
    on e.rateid = z.rateid
    go
    CREATE UNIQUE CLUSTERED INDEX IDXTempTable  ON tbltmptbltest(enrollid)
    create index IDXTemptableDates on tbltmptbltest(ascstartdate,ascenddate)
    go
    select distinct t.*
    from tbltmpgroup t
    where rateid in (
    select distinct t.rateid from VW_ASC_Billing)
    order by billorgid
    set nocount off
    GO
    SET QUOTED_IDENTIFIER OFF
    GO
    SET ANSI_NULLS ON
    GO

    Please post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Learn how to follow ISO-11179 data element naming conventions and formatting rules (you have no idea).
    Temporal data should use ISO-8601 formats. Code should be in Standard SQL as much as possible and not local dialect. 
    What you did post is bad SQL. 
    The prefix “tbl-” is a design flaw called tibbling and we do not do it. We seldom use temp tables in RDBMS; it is how magnetic tape file programmers fake scratch tapes. 
    If the schema is correct, then SELECT DISTINCT is almost never used. 
    Your “bill_parent” looks like a assembly language bit flag; we never use those flags in SQL. 
    “Funding_Type_Status” is an absurd name for a table. A status is a state of being, not an entity. A type is an attribute property. So this table ought to be column that is either a “funding_type” or “funding_status” (with the time period for the state of being
    shown in other columns). But this hybrid is not possible in a valid data model. 
    Want to try again, with DDL and some specs? 
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • How to send email using pl/sql containing the result set as the msg body

    Hi.. im using Pl/SQL code to send emails to the users from a dataset that is obtained in a databse table. i have used utl_smtp commands to establish the connection with the smtp mail server. im stuck at the logic when i have to include the message body which is actually the result set of a table.. For instance
    IF (p_message = 0) THEN
    UTL_SMTP.write_data(l_mail_conn, 'There is no mismatch between the codes' || UTL_TCP.crlf);
    ELSE
    UTL_SMTP.write_data(l_mail_conn, 'The missing codes are ' || UTL_TCP.crlf);
    for s in (select * from temp)
    loop
    UTL_SMTP.write_data(l_mail_conn, ' ' ||s || UTL_TCP.crlf);
    end loop;
    END IF;
    UTL_SMTP.close_data(l_mail_conn);
    UTL_SMTP.quit(l_mail_conn);
    END;
    ***p_message is a prameter passed to this procedure..
    Can i obtain the result in the form i have it in my table. which has three columns. I want to display the three columns as it is with teh records. ?

    this is not related about this forum but you can use below,
    CREATE OR REPLACE PROCEDURE SEND_MAIL (subject varchar2,mail_from varchar2, mail_to varchar2,mail_msg varchar2)
    IS
    mail_host varchar2(30):='XXXXX';
    mail_conn utl_smtp.connection;
    tz_offset number:=0;
    str varchar2(32000);
    BEGIN
    begin
    select to_number(replace(dbtimezone,':00'))/24 into tz_offset from dual;
    exception
    when others then
    null;
    end;
    mail_conn:=utl_smtp.open_connection(mail_host, 25);
    utl_smtp.helo(mail_conn,mail_host);
    utl_smtp.mail(mail_conn,'[email protected]');
    utl_smtp.rcpt(mail_conn,mail_to);
    utl_smtp.open_data(mail_conn);
    utl_smtp.write_data(mail_conn,'Date: '||to_char(sysdate-tz_offset,'dd mon yy hh24:mi:ss')||utl_tcp.crlf);
    utl_smtp.write_data(mail_conn,'From: '|| mail_from ||utl_tcp.crlf);
    utl_smtp.write_data(mail_conn,'To: "'|| mail_to ||'" <'||mail_to||'>'||utl_tcp.crlf);
    utl_smtp.write_data(mail_conn,'Subject: '||subject||utl_tcp.crlf);
    utl_smtp.write_data(mail_conn,utl_tcp.crlf);
    utl_smtp.write_data(mail_conn,replace_turkish_chars(mail_msg)||utl_tcp.crlf);
    utl_smtp.write_data(mail_conn,utl_tcp.crlf);
    utl_smtp.close_data(mail_conn);
    utl_smtp.quit(mail_conn);
    END;
    Edited by: odilibrary.com on Jun 12, 2012 5:26 PM

  • How to get the result set in batches

    I have a query which results into large data. This data i want to display in a group of 20. After every 20 records i want to add header and footer to it.
    Is it possible to get the result set data into batch of 20 ? means can i specify start and end index of query ?
    regards
    Manisha

    What I am saying is that a big query with lots of
    joins will probably be slow, and as such would be a
    ripe candidate for batching the responses, if it were
    not possible to speed/optimize it. Batching is nice
    to look at for the user, but is not a solution for
    performance problems. In essence it is irrelevant
    that it adds a little performance deficit, as it
    appears to be running a lot quicker, and gives more
    feedback to the user.Then let me say it again....
    - "Join" is a term that applies to a method of doing queries in the database....
    - Query 1 which uses a join and returns 15 rows
    - Query 2 which does not use a join and returns 1500 rows.
    Given the above then Query 1 will provide better overall performance for the system than Query 2 in a properly configured database.
    If it doesn't then the database is not set up correctly.
    And again this will be irrespective of whether the query is scrollable or not.

Maybe you are looking for

  • Can the cover on the macbook pro be closed while playing music?

    can the cover on the macbook pro be closed while playing music?

  • How to create sequence when minvalue is unknown?

    I am currently migrating a lot of tables (that already have data) over to using sequences. I'd like to have a script that creates these sequences without having to hardcode the minimum value that the sequence should start at. I am trying to do someth

  • Restriction for the use of last_record in 10g forms

    Hi, When I was working on Forms 6i with the query in the trigger When_new_form_instance: go_block('ABC'); execute_query; last_record; first record; go_block('DEF'); execute_query; last_record; first record; It worked and gave correct data on frontend

  • Uploadfile

    Hello all, I am using jdeveloper 11.1.2.3.0 I am using a train of 3 steps to add a new row to a table in the database. In the last step, I have to upload a file and save the path of the uploaded file to the database. I am uploading the file correctly

  • Determine hot blocks on interconnect

    Hi, I got the below query from the forum...Re: How to determine hot blocks on interconnect and when i ran in my instance.. its show as SQL> select /*+ rule */ de.owner, de.segment_name, de.segment_type,   2    3  ash.event,   4  sum(ash.time_waited)