Query a resultset in java like CFQUERY

Hello,
Is there a way to query a resultset in java. Yes what I mean is after obtaining one resultset, again query on that resultset like we do to a table in the DB.
Here is my problem in detail and any help doing the same in Java will be most appreciated :-)
I am working on a peculiar problem where we are moving our application from cold fusion to Java. Cold fusion being very powerful for database oriented applications my project was initially developed using CF and uses a lot of advanced features of CF. However the need to move to java was soon realised due to various reasons. Now one of the main problems we are facing is the CFQUERY tag in cold fusion.
This tag lets you create a resultset by
<cfquery name="aaa" datasource="blah-blah">
QUERY COMES HERE
</cfquery>
The best part is.... you can also query the above resultset obtained as follows:
<cfquery name="bbb" dbtype="query">
SELECT * from aaa where ***************
</cfquery>
We have used it so often in CF since it significantly reduces the query throughput times. Now we would love to find a way to do the same in Java.
Any ideas
Thanks
Karen

Yes thats one way of working with it. But the problem
is we are dealing with very huge volume of data and
hence querying an already existing resultset is the
best option and has been working very well with our
kind of project too. We also have several concurrent
users doing the same which adds more load on the DB so
doing it from the CF/Java end seems a better choice
for us.I understand your sentiment, but having worked with applications trying to 'port' applications to new technologies I would have some concerns with your approach. Rather then 'port' the application I would suggest that you will have to re-engineer the application. This is more true for larger systems where larger system is heavy mulit-user, or large database access. It is also more true for applications moving from procedural to object based languages.
I don't agree that you are better off manipulating data on the application server. In my experience I have found that data manipulation is optimized when running as close to the database as possible (for the reasons listed in my previous post). So if you decide to re-engineer you may want to consider this in your design decisions.
We already have the DB so we are not even considering
looking for another one. BTW we're using SQL SERVER.Well, as long as you don't have too many users (darn that original sybase lock manager) :-)
I too can't think of a way to get this done using Java
like CF. Hmmm .... yeah if nothing else then we'll
have to change the way we work all together.I have no experience in using it, but user "cluckcluck" posted the following. Might be something to take a look at. This is similar to what I was talking about when using embedded Java databases like Cloudscape, but this works with external databases:
"An excellent solution for this sort of problem is Hibernate (www.hibernate.org) a DB independent ORM persistance layer. Each data source would need to be defined, and each datasource would have its own SessionFactory but once this mapping and config is done you can treat the contents of the DB as POJOs, and perform queries against them. Its not so generic that you wouldn't still have to know which data model the entity you are after is in..."
Good Luck!

Similar Messages

  • Create a CF Query Result Set in Java

    I'd like to programatically build a ColdFusion query resultset inside of a Java class and return it to the calling application.  See the Java psudocode below to see what I'm talking about:
    public class MyClass {
         public coldfusion.sql.QueryTable getQuery() {
              // Create a query table object
              QueryTable myTable = ..?
              // Loop through some set of instance data for my class
              for(int c = 0; c < this.myWigets.length; c++) {
                   int row = c+1;
                   myTable.setField(row, nameCol, this.myWigets[c].name);
                   myTable.setField(row, colorCol, this.myWigets[c].color);
              return myTable;
    I've had stuff like this partially working in the past but had issues with things like query of queries and such probably due to the hacks used to create the QueryTable object.  I'm mainly just checking in to see if there has been any progress made in this area.  To me this seems like such an obvious thing for a Java developer working within CF to want to do.  I'm surprised Adobe doesn't have an officially supported API for doing this sort of thing (or maybe I'm just too dumb to find it.)    A few other notes... I'm not using CFX, and I'm not starting with a java.sql.ResultSet otherwise I would use the QueryTable(java.sql.ResultSet) constructor.  I need to build this thing from scratch programatically.
    Thanks for your time.  I hope this question makes sense to someone out there.
    - Mike

    I appologize.  I wasn't very clear with my original question.
    I'm creating an instance of my Java class from within CF using createObject("java", "com.example.MyClass").  So based on the sample code in my original post on the CF side I'd like to do something like this:
    <cfscript>
         myObj = createObject("java", "com.example.MyClass");
         myObj.doSomeStuff();
         myCFQuery = myObj.getQuery();  // Return a CF query from my java class
    </cfscript>
    ... then do stuff like ...
    <cfquery name="mySortedQuery" dbtype="query">
         select     *
         from       myCFQuery
         order      by color
    </cfquery>
    I appriciate your suggestions so far.  I have other solutions working already but they are not ideal.  I was just hoping someone had a clean and as-hack-free-as-possible way of creating a ColdFusion query result set in Java and passing it back to CF.
    Thanks again,
    Mike

  • Problem with return a ColdFusion query object from a Java class

    Hi!
    I need to return a ColdFusion query object from a Java class
    using a JDBC result set ( java.sql.ResultSet);
    I have tried to pass my JDBC result set in to the constructor
    of the coldfusion.sql.QueryTable class with this code:
    ColdFusion code
    <cfset pra = createObject("java","QueryUtil").init()>
    <cfset newQuery = CreateObject("java",
    "coldfusion.sql.QueryTable")>
    <cfset newQuery.init( pra.getColdFusionQuery () ) >
    My java class execute a query to db and return QueryTable
    Java code (QueryUtil.java)
    import coldfusion.sql.QueryTable; // (CFusion.jar for class
    QueryTable)
    import com.allaire.cfx //(cfx.jar for class Query used from
    QueryTable)
    public class QueryUtil
    public static coldfusion.sql.QueryTable
    getColdFusionQuery(java.sql.ResultSet rs)
    return new coldfusion.sql.QueryTable(rs);
    but when i run cfm page and coldfusion server tries to
    execute : "<cfset pra =
    createObject("java","QueryUtil").init()>" this error appears:
    Object Instantiation Exception.
    An exception occurred when instantiating a java object. The
    cause of this exception was that: coldfusion/sql/QueryTable.
    If i try to execute QueryUtil.java with Eclipse all it works.
    Also I have tried to return java.sql.ResultSet directly to
    coldfusion.sql.QueryTable.init () with failure.
    Do you know some other solution?

    ok
    i print all my code
    pratica.java execute a query to db and return a querytable
    java class
    import java.util.*;
    import java.sql.*;
    import coldfusion.sql.*;
    public class Pratica {
    private HashMap my;
    private String URI,LOGIN,PWD,DRIVER;
    private Connection conn=null;
    //funzione init
    //riceve due strutture converite in hashmap
    // globals
    // dbprop
    public Pratica(HashMap globals,HashMap dbprop) {
    my = new HashMap();
    my.put("GLOBALS",globals);
    my.put("DBPROP",dbprop);
    URI = "jdbc:sqlserver://it-bra-s0016;databaseName=nmobl";
    LOGIN = "usr_dev";
    PWD = "developer";
    DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
    try{
    // Carico il driver JDBC per la connessione con il database
    MySQL
    Class.forName(DRIVER);
    /* Connessione alla base di dati */
    conn=DriverManager.getConnection(URI,LOGIN,PWD);
    if(conn!=null) System.out.println("Connection Successful!");
    } catch (ClassNotFoundException e) {
    // Could not find the database driver
    System.out.print("\ndriver non trovato "+e.getMessage());
    System.out.flush();
    catch (SQLException e) {
    // Could not connect to the database
    System.out.print("\nConnessione fallita "+e.getMessage());
    System.out.flush();
    //funzione search
    //riceve un hash map con i filtri di ricerca
    public QueryTable search(/*HashMap arg*/) {
    ResultSet rs=null;
    Statement stmt=null;
    QueryTable ret=null;
    String query="SELECT * FROM TAN100pratiche";
    try{
    stmt = conn.createStatement();// Creo lo Statement per
    l'esecuzione della query
    rs=stmt.executeQuery(query);
    // while (rs.next()) {
    // System.out.println(rs.getString("descrizione"));
    catch (Exception e) {
    e.printStackTrace();
    try {
    ret = Pratica.RsToQueryTable(rs);
    } catch (SQLException e) {
    e.printStackTrace();
    this.close();
    return(ret);
    // ret=this.RsToQuery(rs);
    // this.close(); //chiude le connessioni,recordset e
    statament
    //retstruct CF vede HashMap come struct
    //METODO DI TEST
    public HashMap retstruct(){
    return(my);
    //conversione resultset to querytable
    private static QueryTable RsToQueryTable(ResultSet rs)
    throws SQLException{
    return new QueryTable(rs);
    //chiura resultset statament e connessione
    private void close(){
    try{
    conn.close();
    conn=null;
    catch (Exception e) {
    e.printStackTrace();
    coldfusion code
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01
    Transitional//EN">
    <html>
    <head>
    <title>Test JDBC CFML Using CFScript</title>
    </head>
    <body>
    <cftry>
    <cfset glb_map =
    createObject("java","java.util.HashMap")>
    <cfset dbprop_map =
    createObject("java","java.util.HashMap")>
    <cfset glb_map.init(glb)> <!---are passed from
    another page--->
    <cfset dbprop_map.init(glb["DBPROP"])>
    <cfset pra =
    createObject("java","Pratica").init(glb_map,dbprop_map)>
    <cfset ourQuery
    =createObject("java","coldfusion.sql.QueryTable").init(pra.search())>
    <cfcatch>
    <h2>Error - info below</h2>
    <cfdump var="#cfcatch#"><cfabort>
    </cfcatch>
    </cftry>
    <h2>Success - statement dumped below</h2>
    <cfdump var="#ourQuery#">
    </body>
    </html>
    error at line <cfset pra =
    createObject("java","Pratica").init(glb_map,dbprop_map)>
    An exception occurred when instantiating a java object. The
    cause of this exception was that: coldfusion/sql/QueryTable.
    -----------------------------------------------------------------------

  • Size Limitation for ResultSet  in JAVA

    when i execute a query as
    ResultSet rs=st.executeQuery("select ....")
    It throws an error saying "Please Use Server Side Cursor for large resultset"...
    But when i execute the same in SQL Query Analyzer, it returns the row properly without any issue...
    When i try the same in application... it couldnt return the rows to the ResultSet......
    Can anyone say, what must be done to get the rows properly in the java servlet program..??? One thing is the result returned from this query will be large...may be more than 10000 rows..
    Anyone say, what is server side cursor in JAVA???
    stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                        ResultSet.CONCUR_READ_ONLY);
    rs = stmt.executeQuery(strSql);
    Is this the server side cursor??... what impact will it have when executed...???
    Please help me out...
    Thanks in Advance...

    Hi,
    Thanks for the link, but I didn't see any answers for
    my question.....my question is if there is a way that
    ResultSet hold all the query results?
    Thanks again,
    KatieDid you read this part:
    " Result Set Limitations and Downgrade Rules
    Some types of result sets are not feasible for certain kinds of queries. If you specify an unfeasible result set type or concurrency type for the query you execute, the JDBC driver follows a set of rules to determine the best feasible types to use instead.
    The actual result set type and concurrency type are determined when the statement is executed, with the driver issuing a SQLWarning on the statement object if the desired result set type or concurrency type is not feasible. The SQLWarning object will contain the reason why the requested type was not feasible. Check for warnings to verify whether you received the type of result set that you requested, or call the methods described in "Verifying Result Set Type and Concurrency Type".
    - There was a part after that that also talked about work arounds.

  • New java-like scripting language w/ powerful regex

    Hi,
    Just wanted to let you know that there's now a new scripting language called P~ with the following important aspects:
    1) matches and exceeds Perl regex solveability -- e.g. offers full regex-based boolean query on non-indexed corpus, offers completely general side-effects, more accurate than Perl code assertions
    2) basic grammar is very Java like
    3) regex grammar is algebraic, not metacharacter-based, leads to more readable and maintainable solutions to hard problems
    4) offers an easy tool to debug matching behavior of your regexes (rules)
    5) though a full featured scripting language, you can write scriptlets and call them from Java classes, with arguments. Allows you to use your regex solutions in Java applications.
    6) the language is offered as a Java library, as well as a standalone application that runs the library. This means that your scripts can import java classes available in the classpath, you can leverage existing Java libraries.
    Check out the website and try it out: http://ptilde.pbwiki.com
    Andy

    True to an extent. We don't yet have lookaround assertions and won't have backreferencing any time soon. But there are same-time assertions which offer much of the same, and allow for boolean query.
    More accurate general statement insertion side-effects (than Perl code assertions) means that your statements are executed if and only they wrap a subpattern that is part of the ultimate best match -- Perl code assertions execute when the automata encounters them, even if where they are in the regex is ultimately not part of the match, or even if there is no match at all. This aspect is a huge part of the solveability advantage.
    As to the regex test cases, there are about 1000, and we will post them soon.

  • Querying windows service from Java

    Hi All,
    i have a java web application running on jboss that does data collection by querying different windows processes like MSSQLSERVER, IIS availability etc.
    The problem i am facing is that my application is returning a negative result for the above services but when i run the query from command prompt i get a positive result. I dont understand why this happens.
    would really appreciate a response.

    Is query this from java Runtime.exec and from command prompt different? My code creates a string of sc \\<server> query W3SVC and calls this like:               String cmd = "sc "+ " \\\\ " + serverIPOrHostName + "query"+ service;
                   p = r.exec(cmd);
                   inp = p.getInputStream();
                byte[] dataInput = new byte[320];
                inp.read(dataInput);
                String inputData = new String(dataInput);
                //Logger added to read the service response.
                logger.info(inputData);
                //Checks for specified sequence of characters in the string and
                //returns boolean.
                if (inputData.contains(SERVICE_RUNNING)) {
                     result = 1;
                } else {
                     result = 0;
                }My reasoning is that if i cant do it in java because of some security policy then i should not be able to do it in command prompt too? But that is not the case. I can do it over command prompt but not from java code!
    If this is a windows related issue, how should i proceed to debug it? how can i provide access to my java code to do this?
    I happened to check out one site http://www.kbalertz.com/kb_Q323790.aspx where it says that "The File and Printer Sharing for Microsoft Networks component must be turned on for many remote-management functions to work. "
    But this looks like a very trivial (although i dont know much about windows security policies).
    thanks,
    Dilip
    PS: Thanks for looking into the mail and responding.

  • Execute BI Query in Web Dynpro Java

    Dear All,
    I have a requirement where i have to display of traffic light that sets its color based on the outcome of a SAP BEx query using Web Dynpro Java.
    Please explain me the steps how to retrieve and execute the SAP BEx query  using WDJ.
    Thanks & Regards
    Rajeev

    Hi Rajeev
    You can refer to the following links :
    [How to execute a BI query/view from a web dynpro application?]
    [How to send query parameters using BIApplicationFrame]
    Regards,
    Sayan Ghosh

  • Query is throwing an error like missing right paranthesis.,

    Hi,
    The below query is throwing an error like missing right paranthesis.,
    and Is there any way to write the same query in a simpler way ?
    SELECT AVALABLEBALANCE
    FROM (
    ( SELECT SUM(TH1.TRANSACTIONAMOUNT)
    FROM TRANSACTIONHISTORY TH1,
    TRANSACTIONTYPE TT,
    CARDDETAIL CD,
    P2P_CARDDETAIL P2P
    WHERE TH1.TRANSACTIONTYPEID = TT.TRANSACTIONTYPEID
    AND TH1.CARDID = CD.CARDID
    AND CD.CARDID = P2P.CARDID
    AND TH1.CARDID = 6013
    AND TT.TRANSACTIONTYPECODE IN ('WITHDRAWAL_CHECK_FEE')
    AND TRUNC(TH1.TRANSACTIONDATETIME) = TRUNC(TH3.TRANSACTIONDATETIME)
    GROUP BY TH1.TRANSACTIONTYPEID,TH1.CARDID,TRUNC(TH1.TRANSACTIONAMOUNT)) -
    ( SELECT SUM(TH2.TRANSACTIONAMOUNT)
    FROM TRANSACTIONHISTORY TH2,
    TRANSACTIONTYPE TT,
    CARDDETAIL CD,
    P2P_CARDDETAIL P2P
    WHERE TH2.TRANSACTIONTYPEID = TT.TRANSACTIONTYPEID
    AND TH2.CARDID = CD.CARDID
    AND CD.CARDID = P2P.CARDID
    AND TH2.CARDID = 6013
    AND TT.TRANSACTIONTYPECODE IN ('FUND_TRANSFER_RECEIVED')
    AND TRUNC(TH2.TRANSACTIONDATETIME) = TRUNC(TH3.TRANSACTIONDATETIME)
    GROUP BY TH2.TRANSACTIONTYPEID,TH2.CARDID,TRUNC(TH2.TRANSACTIONAMOUNT))
    ) T , TRANSACTIONHISTORY TH3
    WHERE TH3.CARDID = 6013

    Hi Sekar,
    Here is your formatted code:
    /* Formatted on 2007/11/16 16:42 (Formatter Plus v4.8.0) */
    SELECT avalablebalance
    FROM ((SELECT SUM (th1.transactionamount)
    FROM transactionhistory th1,
    transactiontype tt,
    carddetail cd,
    p2p_carddetail p2p
    WHERE th1.transactiontypeid = tt.transactiontypeid
    AND th1.cardid = cd.cardid
    AND cd.cardid = p2p.cardid
    AND th1.cardid = 6013
    AND tt.transactiontypecode IN ('WITHDRAWAL_CHECK_FEE')
    AND TRUNC (th1.transactiondatetime) =
    TRUNC (th3.transactiondatetime)
    GROUP BY th1.transactiontypeid,
    th1.cardid,
    TRUNC (th1.transactionamount))
    MINUS
    (SELECT SUM (th2.transactionamount)
    FROM transactionhistory th2,
    transactiontype tt,
    carddetail cd,
    p2p_carddetail p2p
    WHERE th2.transactiontypeid = tt.transactiontypeid
    AND th2.cardid = cd.cardid
    AND cd.cardid = p2p.cardid
    AND th2.cardid = 6013
    AND tt.transactiontypecode IN ('FUND_TRANSFER_RECEIVED')
    AND TRUNC (th2.transactiondatetime) =
    TRUNC (th3.transactiondatetime)
    GROUP BY th2.transactiontypeid,
    th2.cardid,
    TRUNC (th2.transactionamount))) t,
    transactionhistory th3
    WHERE th3.cardid = 6013
    -Edit: Lol this forum's text box does not have a proper formatter to show our codes perfectly :(.. Very sorry about the expected format here.. Lol !!
    ***Lol Poor Format***
    Message was edited by:
    user599090
    I replaced the '-' with MINUS Keyword. That was the mistake you made i guess.

  • SQL query to ResultSet

    I've been stuck on this little problem for a while: I'm trying to pass in two dates, startDate and endDate, which the user inputs, into a database query using the following SQL statements:
    String totalquantity =
    "SELECT SUM(quantity_) AS quantity " +
    "FROM FILLTABLE " +
    "WHERE time_ >= TO_DATE('startDate','mm/dd/yyyy') " +
    "AND time_ < TO_DATE('endDate','mm/dd/yyyy') " +
    After compiling gives me no error, I run the code and obtain an error in the following line, where i'm trying to assign the result of my query to ResultSet, and stops the program from running:
    ResultSet rs = stmt.executeQuery(totalquantity);
    Am I doing something wrong? can someone help? thanks!

    Hi!
    Compiler doesn't bring errors because the String is concatinated correctly and the argument to stmt.executeQuery() is a valid String so syntactically everything is fine. What the compiles doesn't know is that the String contains wrong sql-syntax. This gives you a runtime error while stmt.executeQuery(). Here your servlet receives an error from your databaseserver that complaint about the wring sql-syntax.
    This is the reason for compiling but not running so you will have to check your query string. But Sudha pointed you in the correct direction already so it should be no more problem.
    Thomas.

  • How to create search function (af:query) using method in java

    hi All..:)
    i got problem with search custom (af:query), how to create search function/ af:query using method in java class?
    anyone help me....
    thx
    agungdmt

    Hi,
    download the ADF Faces component demo sources from here: http://www.oracle.com/technetwork/testcontent/adf-faces-rc-demo-083799.html It also has an example for creating a custom af:query model
    Frank

  • Can we execute a query in resultset while loop

    can we execute a query in resultset while loop
    for ex:
    rs=st.executeQuery("SQL");
    while(rs.next())
    rs1=st.executequery("SQL1");
    while(rs1.next())
    }

    If you do this, you lose "rs". Create a second
    Statement object for the other query.This is right. We have done it many times, It is not the issue as long as you use different statement with in the body of the loop

  • Can we execute a query in resultset of while loop

    can we execute a query in resultset while loop
    for ex:
    rs=st.executeQuery("SQL");
    while(rs.next())
    rs1=st.executequery("SQL1");
    while(rs1.next())
    }

    yup no problem..if it doesn work declare the second one as st1

  • Adding two ResultSets in java

    How can we add two resultsets in java ?

    screen_simu wrote:
    Is it something we can do in java?OP, if you can do it in SQL, that likely would be better. On the other hand, do you mean that want to add the results from two resultsets that might perchance be different? IOW ... if both ResultSets produce the same columns, then a UNION join in SQL:select
        tableA.empl_name,
        tableA.empl_id
      from tableA
    UNION
    select
        tableB.empl_name,
        tableB.empl_id
      from tableBBut, if you want to select out specific columns from differing RS's, then you might want to do this:
      List<Empl> empList = new ArrayList<Empl>();
      public class Empl {
        private String empl_id;
        private String empl_name;
        private Double empl_wage;
        public void setName(String name) {
          empl_name = name;
    // ... etc, other method implementations ...
    // ... SQL stuff ...
      String sqlA =
         "select"
        +"    tableA.empl_id,"
        +"    tableA.empl_wages"
        +"  from tableA";
    // ... rsA is the ResultSet from the tableA selection
      Empl empl = null;
      while (rsA.next()) {
        empl.setID(rsA.getString(1));
        empl.setWage(rsA.getDouble(2));
        empl.setName(processTableB(empl.getID()));
        empList.add(empl);  // new Empl Object for each employee
      public String processTableB(String id) {
        String name = null;
      String sqlB =
        "select"
        +"    tableB.empl_name"
        +" from tableB"
        +" where tableB.empl_id = ?"
    // ... set up PreparedStatement ... using passed in id
    // ... process ...
      while (rsB.next()) {
        name = rsB.getString(1);
      return( name );
    }Above code untested, but hopefully you get the idea.

  • Determining free disk space in a platform independent "java-like" way?

    how can i determine free disk space in a platform independent "java-like" way?

    Search the forum "free disk space".

  • I hope to develop a function with java like IE's save as.How can I do?

    I hope to develop a function with java like IE's save as.How can I do?

    hi ,
    Considering IE browser page as an object, U can use Serialization where u can save that object.(i.e state of the object) And then when u open it thru de-serialization, u can restore the page/object .
    Hope that helps U .
    Techie.

Maybe you are looking for

  • Unable to view video with 3.0.4

    I am trying to watch a video on a U. of Illinois web site, and I get a notice that I need Safari 2.0. Certainly my 3.0.4 should work as well as 2.0 - yes? Is there something I am missing? Dennis

  • Register marks move to top of imposed PDF after color convert

    I have an imposed PDF made up of 16 smaller files...It is imposed from Metrix and it creates a PDF. I need to map the spot colors onto the color bar...I go to (ink manager) change the colors then (color convert) to map the colors and the register mar

  • Gif animation k changes once saved

    When I "save for web" a gif animation in photoshop its optimized at 72k.  I then check it in file manager and its 102k???!!!

  • HT4528 My Iphone 4 will not open any apps.

    Why won't my Iphone 4 allow any apps to open?

  • Can't get granular file .bak or .cmp to restore.

    I made a granular backup of my site collection into .bak. and now im trying to import said file by using I have the site I'm importing to already created at http:/testserver/sites/test Import-SPWeb -identity http:testserver/sites/test -path \\shareds