Convert result set into input stream

Hi,
I have result set with me having 93 columns with 1 lac rows. I want to download the result set as xls file.
Because of the data set size is large, i'm not able to hold the data in java object. So i'm trying to convert result set to input stream and giving this input stream to servlet output stream by specifying the contentType as text/xls.
I'm not able to convert result set into input stream.
Could you provide a solution here...
Thanks,
Rajesh

1 - JDBC is the wrong way to extract this data. It's like "What's the fastest way
to copy the Oxford English Dictionary using tweets?" I would research the
DBMS's bulk extract functionality.
2 - Are you dead-set absolutely sure you need to do this at all? What can you
do with the data all in one flat file that you cannot do with SQL access to the
data?
3 - If you want to convert all the columns into one (not that it's a huge
win or anything), you can use the DBMS's conversion and concatenation
functionality in your SQL. So instead of
"select col1, col2, col3, .... from MyBigTable"
do (change this to whatever conversion function syntax and concat syntax your DBMS needs)
"select convert(col1, varchar) concat ' ' concat convert(col2, varchar) concat ' ' concat convert(col3, varchar) ... from MyBigTable"
so the result set you get is a single column.
Joe

Similar Messages

  • Is my code right about convert file into input stream?

    InputStream is = new FileInputStream(file);
    Parser ps = new Parser(file);
    //create xml document
    TXDocument doc = ps.readStream(is);
    I am using j2sdk1.4 and IBM XML for java Parser v2.0
    Thanks a lot
    D

    1 - JDBC is the wrong way to extract this data. It's like "What's the fastest way
    to copy the Oxford English Dictionary using tweets?" I would research the
    DBMS's bulk extract functionality.
    2 - Are you dead-set absolutely sure you need to do this at all? What can you
    do with the data all in one flat file that you cannot do with SQL access to the
    data?
    3 - If you want to convert all the columns into one (not that it's a huge
    win or anything), you can use the DBMS's conversion and concatenation
    functionality in your SQL. So instead of
    "select col1, col2, col3, .... from MyBigTable"
    do (change this to whatever conversion function syntax and concat syntax your DBMS needs)
    "select convert(col1, varchar) concat ' ' concat convert(col2, varchar) concat ' ' concat convert(col3, varchar) ... from MyBigTable"
    so the result set you get is a single column.
    Joe

  • Put database result set into a vector?

    I have a resultset rs I would like to put into a vector but I don't seem to get something fundamental. I can put individual items in with add() for instance but how do I dump a whole result set in there...
    and if I do so should I turn them all to strings before putting them into the vector?
    Any general advice would be appreciated, I've read a lot about Vectors today and have ended up more confused than I'd have expected. So I have come to seek some basic advice.
    private static void showResult (ResultSet rs) throws SQLException {
                            Vector vector = new Vector();
             try
                     // rs is the resultset output from a database
                                      vector.addAll(rs);
             catch(NullPointerException ex)
                    System.out.println("bugger - null pointer exception");
                    System.out.println();
                    ex.printStackTrace();
    }

    Iterate over the resultset, create your own object to store data for each row and add that object to the vector. There is no escape from this.
    catch(NullPointerException ex)You should not be handling Runtime exceptions. You need to take care not to let them occur through your coding logic.

  • Can I retrieve a result set from Oracle and then incorporate that result set into my main SQL Server Stored Procedure?

    So I have a chunk of data that only resides in Oracle. So I need to capture that information from Oracle. Now before you get over zealous, I did try with an OPENQUERY and it took FOREVER! And I don't know why the OPENQUERY took FOREVER but if I run the same
    query directly against Oracle it runs very quickly...like 20 seconds.
    So now I'm wondering...can I build a dataset in my SSRS Report that uses an Oracle Data source and an Oracle Stored Procedure in its Dataset that I'll create to aggregate this subset of data and then utilize its result set back in my main reporting
    Dataset that will utilize SQL Server? And how can I do that? Can I make my main Dataset reference, say, a #TemporaryTable that is created from my Oracle Dataset in its
    I'll continue to Google a few things as I await your review and hopefully a reply.
    Thanks in advance for your help.

    Hi ITBobbyP,
    According to your description you want to use data from a Oracle data source into a DataSet which retrieving data from SQL Server. Right?
    In Reporting Services, we can have multiple data sources in one project pointing to different database. And we can use separated dataset to retrieve data from different data source. However, it's not supported to combine the two datasets together
    directly. We can only use Lookup(), LookupSet() function to combine fields from different dataset into one tablix when there are common columns between two datasets. This is the only way to make tow result sets together in SSRS.
    Reference:
    Lookup Function (Report Builder and SSRS)
    LookupSet Function (Report Builder and SSRS)
    Best Regards, 
    Simon Hou
    TechNet Community Support

  • Exporting query result set into CSV file using Forms

    Hi ,
    My requirement is
    -> I need to create a form where I have a Multi line text box and two button.
    -> When I enter a query in text box and click on Execute button, It should execute a select query.
    -> After execution, Result set needs to be exported into an Excel file.
    Please give a hint how to do this????
    Thanks,
    maddy

    as you are using text item to write SQL query by the user
    so for that you need to use the exec_sql package to parse the text items query and get definitions and values of the columns being
    resulted in the result set of the query.
    once your query is execute to the desired connection then you need to use fetch the result to the CSV file by use of the TEXT_io package
    which will open the text file with .csv extension and you have to pass the each line to that text file with comma separated values as "ss","rr" etc.
    or you can use the ole2 package to call the excel application and then fetch the data of exe_sql query to that.

  • Concatenate result set into a string SQL

    Hi, I need some help with concatenating a resultset to avoid duplication of data.
    I have 3 tables:
    SCRIPT
    ID - Number PK
    DATE - Date
    TITLE - Varchar2
    AUTHOR
    A_ID - Number PK
    A_Name - Varchar2
    SCRIPT_AUTHOR
    ID - Number - PK, FK to Script.ID
    A_ID - Number PK, FK to Author.A_ID
    I need to list all authors for each script on one line, at the moment I have the following SQL :
    Select S.Title, SA.A.ID
    FROM SCRIPT S, SCRIPT_AUTHOR SA
    WHERE SCRIPT.ID = SCRIPT_AUTHOR.ID
    and as expected this is returning a dataset as follows - giving me 2 lines in this case for one script :
    S.TITLE, SA.A_ID
    1, 1
    1, 2
    What I am actually after is a result set that combines both the authors in this case in one record: 1, 1:2 so I only have 1 line per script.
    The scripts can have many authors, and I will want to do this for many scripts at a time.
    I have hit a blank on how to do this, is it possible to do this with SQL?
    Many Thanks
    p.s. Using: Oracle Database 10g Enterprise Edition Release 10.2.0.3.0

    Hi,
    That's called "String Aggregation"
    [AskTom.oracle.com|http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:2196162600402] shows several different ways to do it.
    I recommend the first one, the user-defined function STRAGG, which you can copy from that page.
    Once you have STRAGG installed, your query is simply
    Select       S.Title
    ,       STRAGG (SA.A.ID)     AS sa_id_list
    FROM       SCRIPT     S
    ,       SCRIPT_AUTHOR SA
    WHERE       SCRIPT.ID = SCRIPT_AUTHOR.ID
    GROUPB BY s.Title;On Oracle 10 (and up) you may have a similar function, WM_CONCAT (owned by WMSYS), already installed.
    WM_CONCAT is not documented, so you may not want to use it in your Production applications.

  • How convert a Set into a List

    Given the following :
    Set<Student>  students = getStudents() ;how would one convert the set students to a List<Students>I was thinking of doing something like :
    Student[] array = students.toArray(new Student [students.size()]);
    List<Student> list=Arrays.asList(array);but it doesn't work

    Thanks.Out of interest though (as a theoretical
    exercise), if one was to use the
    Arrays.asList
    how would it be done?Try this:
    Set<Student> set = getStudents();
    Student[] array = set.toArray(new Student[set.size()]);
    List<Student> list = Arrays.asList(array);

  • What is the best way of converting everything in a result set into a string

    hello folks
    What do you think is the best way of converting everything in a resultset into a string???
    At the moment I'm using
    rs.getString(i);
    everywhere (no matter if the underlying datatype is a date or whatever..) it converts automatically evertything expect NULL into a valid string.
    Are there better (simple to use..) ways?

    I don't see a big switch construct. How about trying the following:
    Call this method from your original method by passing the resultset obtained.
    public String[] convert(ResultSet rs) {
         int col = ((ResultSetMetaData) rs.getMetaData()).getColumnCount();
         String[] record = new String[col];
         int i=0;
         while(rs.next()) {
              if(rs.wasNull()) record[i] = new String();
              else record[i] = rs.getString(i);
              i++;
         return record;
    iDriZ

  • Problems in mapping a result set into IN operator

    i can't for the life of me figure out how to create the following predicate in a mapping:
    WHERE table1.cola NOT IN (SELECT table2.cola
    FROM table2);

    Chris,
    Perhaps you can use the minus operator in your example. I.e.:
    select table1.cola
    minus
    select table2.cola
    This select would result in the set of data you need.
    Mark.

  • How to convert a string into a stream

    Hi,
    Actually, I have developed a small piece of code which is working well with the input from the User Console (Via System.in). The console input may be like 10 + 2. Now, I need to pass the input value through my code (Statically) while instantiate. What should i do?
    The code is -
    public static void main( String[] args )
         throws ParseException, TokenMgrError, NumberFormatException {
              EvalStr2 parser = new EvalStr2(System.in) ; // I need to pass my value as "10+2" instead of System.in
    System.out.println("Result-->>"+parser.Start());
    Waiting for your help.
    Thanks
    Venkatesh

    Why not simply provide EvalStr2 with an overloaded constructor that takes a String as a parameter?
    Also, to learn how to ask a better question, read
    [http://catb.org/~esr/faqs/smart-questions.html]
    luck, db
    edit To post code, use the code tags -- [code]Your Code[/code]will display asYour CodeOr use the code button above the editing area and paste your code between the {code}{code} tags it generates.
    Edited by: Darryl.Burke

  • How to split a result set into n-number ranges, each range has same max-min

    Hi guys,
    suppose there's a table T1(fvalue number),
    we can easily get the MAX and MIN of fvalue, for example, 19 and 5, I need to split them into, for example, 3 ranges, 5-9, 10-14, 15-19, they have the same max-min. And for each range, I need to know the count of rows that fall into this range.
    does anyone have any clues? is there any analytic function i can use to accomplish this?
    many thanks.

    There are the NTILE and WIDTH_BUCKET functions that may be of use. However, I'm not exactly sure what you are after.
    It is always helpful to provide the following:
    1. Oracle version (SELECT * FROM V$VERSION)
    2. Sample data in the form of CREATE / INSERT statements.
    3. Expected output
    4. Explanation of expected output (A.K.A. "business logic")
    5. Use \ tags for #2 and #3. See FAQ (Link on top right side) for details.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • How to convert result rows into comma separated values

    hi,
    Version
    BANNER
    Oracle Database 11g Enterprise Edition Release 11.1.0.7.0 - 64bit Production
    PL/SQL Release 11.1.0.7.0 - Production
    CORE     11.1.0.7.0     Production
    TNS for Linux: Version 11.1.0.7.0 - Production
    NLSRTL Version 11.1.0.7.0 - ProductionQuery
    Select distinct prcdr_code from procedure p where P.PRCDR_CTGRY_LKPCD='P' ;
    Output
    PRCDR_CODE
    0001F
    0001T
    0002F
    0002T
    0003F
    0003T
    0004F
    0005F
    0005T
    0006F
    0006T
    0007F
    0007T
    0008F
    0008T
    0009F
    0009T
    000VA
    000VG
    Desired Output
    0001F,0001T,0002F,0002T .................
    My work
    i tried this .....
    Select distinct wm_concat(prcdr_code) as re from procedure p where P.PRCDR_CTGRY_LKPCD='P'  ;
    But i got ORA-22813: operand value exceeds system limits error
    Please help me ..Thanks,
    P Prakash
    Edited by: prakash on Jan 4, 2012 9:05 AM

    Aggregating CLOB's....
    user defined aggregate function can do it...
    create or replace type clobagg_type as object
      text clob,
      static function ODCIAggregateInitialize(sctx in out clobagg_type) return number,
      member function ODCIAggregateIterate(self in out clobagg_type, value in clob) return number,
      member function ODCIAggregateTerminate(self in clobagg_type, returnvalue out clob, flags in number) return number,
      member function ODCIAggregateMerge(self in out clobagg_type, ctx2 in clobagg_type) return number
    create or replace type body clobagg_type is
      static function ODCIAggregateInitialize(sctx in out clobagg_type) return number is
      begin
        sctx := clobagg_type(null) ;
        return ODCIConst.Success ;
      end;
      member function ODCIAggregateIterate(self in out clobagg_type, value in clob) return number is
      begin
        self.text := self.text || value ;
        return ODCIConst.Success;
      end;
      member function ODCIAggregateTerminate(self in clobagg_type, returnvalue out clob, flags in number) return number is
      begin
        returnValue := self.text;
        return ODCIConst.Success;
      end;
      member function ODCIAggregateMerge(self in out clobagg_type, ctx2 in clobagg_type) return number is
      begin
        self.text := self.text || ctx2.text;
        return ODCIConst.Success;
      end;
    end;
    create or replace function clobagg(input clob) return clob
      deterministic
      parallel_enable
      aggregate using clobagg_type;
    SQL> select trim(',' from clobagg(ename||',')) as enames from emp;
    ENAMES
    SMITH,ALLEN,WARD,JONES,MARTIN,BLAKE,CLARK,SCOTT,KING,TURNER,ADAMS,JAMES,FORD,MILLER
    SQL> ed
    Wrote file afiedt.buf
      1  with t as
      2    (select 'PFL' c1, 0 c2,110 c3 from dual union all
      3     select 'LHL', 0 ,111 from dual union all
      4     select 'PHL', 1, 111 from dual union all
      5     select 'CHL', 2, 111 from dual union all
      6     select 'DHL', 0, 112 from dual union all
      7     select 'VHL', 1, 112 from dual union all
      8     select 'CPHL', 0, 114 from dual union all
      9     select 'WDCL', 1, 114 from dual union all
    10     select 'AHL' ,2 ,114 from dual union all
    11     select 'NFDL', 3, 114 from dual)
    12  --
    13  -- end of test data
    14  --
    15  select trim(clobagg(c1||' ')) as c1, c3
    16  from (select * from t order by c3, c2)
    17  group by c3
    18* order by c3
    SQL> /
    C1                                     C3
    PFL                                   110
    LHL CHL PHL                           111
    DHL VHL                               112
    CPHL AHL NFDL WDCL                    114

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

  • Combining result set of two services into one result set

    Hi,
    I have a model where I am getting one result set (6 Fields) from BI query and another result set (3 Fields which gives real time values) from OLTP system. I want to show the output of these two result sets into single result set (7 Fields). I have a common field in both the result sets as key field.
    I tried this using UNION operator but I am not able to set the Key fields and also in the table view of UNION operator I am getting any field to be added to table.
    Can anyone help me to solve this problem?
    Any help is appreciated.
    Regards,
    Amit

    Hi Amit,
    in this case, you have to use the combine-operator. However, this operator needs a key-field in each of these sets. E.g. Combine set (<u>customer-id</u>, order-id, week, delivery-state) with set (<u>customer-id</u>, city, client-class).
    The combine operator might not be available when compiling to webdynpro, I did not check that.
    Best Regards, Benni

  • Overwriting result sets in a file

    Hello, I am querying a database and putting the results into a ResultSets. When the user clicks a button the results are written to an Excel worksheet. However, each time you click the button or write to the worksheet, the ResultSet is appended to the previous one. Is there a way to overwrite??? Thank you in advance.

    here is the method I created to insert a result set into MS Excel
    public void output_vehicleInfo(ResultSet rset)
    try{
    prepared_statement = con.prepareStatement("insert into \"VehicleInfo$\" (BumperNumber, Noun, Section) values (?, ? ?)");
    while(rset.next())
    prepared_statement.setString(1,rset.getString(1));
    prepared_statement.setString(2,rset.getString(2));
    prepared_statement.setString(3,rset.getString(3));
    prepared_statement.execute();
    //catch clause
    The code works; however, it doesn't insert at the beginning of the table. It inserts after the last record. I want to overwrite all data with the insert.

Maybe you are looking for

  • Impossible to test or debug on iPad application

    Hello, I'm trying to test my AS3 application done in Flash CC pro 2014 v14.1.0.96 with the command menu "test on the USB Device" or "debug on USB device", but it always says that my device are not connected ! (although of course they are) It worked o

  • DHCP beginning address problem.

    Hi guys, I cannot understand how to configure my TC. I put exactly the same network settings as they were in the Airport Express to share the Internet connection. Everything works fine except the internet itself. The problem as I see it is that dhcp

  • Moving Custom fields to the main screen in CUP

    Hi Gurus, I am wondering if there is a way to move a custom field to the main screen like under general information instead of it being in the more section. We have a custom field which would be mandatory, So it would be nice to have it on the main s

  • Copy/paste shapes from Illustrator also brings in a black background. Why?

    When you copy/paste a shape from Illustrator into Muse, it also brings in a black background. Why does this happen and how do we delete it? Thanks!

  • Enable/Disable Buttons/Lists

    How do you set a JButton to not be able to be clicked and a JList not be able to alter the selection?