Creating a dynamic prepared statement

the problem:
i have a range of paratmeters coming in from a form and need to be able to create a dynamic query string to go into a prepared statement object.
the problem i have is there are 2 fields year range and year.
if year range is none i need to create the query string as such :
where the value of year can be serached on exactly
str.append("VOLUME_YEAR = ? ");the probelm is if the year range is 5 or year range is 10 i dont know how to maipulate the query string to be able to set the string such that i can then place the year value in the place holder in preparedStatement.setInt(1, year)
how can i create the intial query string ie.- what are the possible things that i can do. - i'm thinking of things like putting some type of between or such type query statement - but not at all sure how the syntax would go - ie. how would i use the year value and how would i create this dynamic part of the query string so that the JDBC regonises it?
thanks for any help.
public String setVolumeYearQuerySt(String year, String yearRange, StringBuffer str){
          String volumeYearQueryString = null;
          Sring doAction= null;
          if (yearRange.equals("None")){str.append("VOLUME_YEAR = ? ");}
          else if(yearRange.equals("5 Years")){doAction = "Nothing";}
          else if (yearRange.equals("10 Years")){doAction = "Nothing";}
          return volumeYearQueryString;
          }

Please do not cross-post:
http://forum.java.sun.com/thread.jspa?threadID=686789&tstart=0
- Saish

Similar Messages

  • Creating a Dynamic Update Statement based on Select

    hi,
    i'm trying to create a dynamic update statement based on select statement
    my requirment is to query a joint tables and get the results then based on the results i need to copy all the data and create an update statement for each row
    for ex
    the update statement should look like this
    update iadvyy set SO_SWEEP_CNT = '1' where inst_no = '003' and memb_cust_no = 'aaaaaaaaaaaaaaaa';
    and the select statement like the following
    select substr(key_1,11,9) account_no,sord_mast SO_SWEEP_CNT from
    select acct_no,count(*) sord_mast from
    (select from_acct_no acct_no,update_mast
    from sord where FROM_SYS in ('DEP','INV') and TERM_DATE > 40460
    union all
    select to_acct_no acct_no,update_mast
    from sord where TO_SYS in ('DEP','INV') and TERM_DATE > 40460)
    group by Acct_no)
    right outer join
    invm
    on
    key_1 = '003'||acct_no
    where sord_mast > 0;
    so taking the above two columns from the above select statement and substitue the values as separate update statement.
    is that doable , please share your knowledge with me if poosible
    thanks in advanced

    is that doable , please share your knowledge with me if poosibleyes
    The standard advice when (ab)using EXECUTE IMMEDIATE is to compose the SQL statement in a single VARCHAR2 variable
    Then print the SQL before passing it to EXECUTE IMMEDIATE.
    COPY the statement & PASTE into sqlplus to validate its correctness.

  • Dynamic Prepared statement--pls help

    I need to create a prepared statement where i do not know how many parameters( or arguments i.e " ? ") will be passed. The arguments are decided dynamically while runtime...as in i may pass only a single argument or many.
    example:
    select * from employee_table where employee_id in (?,?....)
    in the above query i may only one employee_id or may be more than one.This is decided during run time.I do not want to run a for loop for the number of employee is as this will cause performance issue. can anybody please tell me how these arguments can be generated dynamically
    thanks 4 ur help in advance

    When will you know the emp.Id ?
    Reason is Once you get the emp.Id at runtime means you can assign this id to string variable using the comma separator and assigned this string to the query.
    Example
    String listOfEmpId = "e11,ee23,e55..."; and then use this variable in the query.

  • Creating a dynamic sql statement

    hi,
    I am having a query
    select w.id, w.cr_dt, w.cc_cor_addr_id, w.cc_cee_addr_id,
    w.ttl_pkgs, w.chrg_wt, wf.wb_bkg_chgd_amt + wf.wb_bkg_chgd_amt_st
    from ops_waybl_fin wf, ops_waybl w
    where wf.id = w.id
    and cre_bill_batch_dtls_id in (select get_bill_batch(1) from dual);
    the bold part is a function returns a select query.
    if the sql statement is run then we get data based on which the parent query returns data.
    how we should use a function that returns select query.
    Please advice..

    *** not tested *** Sven probably had in mind something like
    with
    v_count_cust_no as
    (select count(orr.param_val) the_count
       from ops_report_req orr
      where orr.id = :p_req_id
        and orr.param_nm = 'CUST_ID'
    v_count_cust_cntr as
    (select count(orr.param_val) the_count
       from ops_report_req orr
      where orr.id = :p_req_id
        and orr.param_nm = 'CUST_CNTR_ID'
    variant as
    (select case when (select the_count from v_count_cust_no) > 0
                 then case when (select the_count from v_count_cust_cntr) > 0
                           then 1
                           else 2
                      end
                 else case when (select the_count from v_count_cust_cntr) > 0
                           then 3
                           else 4
                      end
            end the_type
       from dual
    select w.id,w.cr_dt,w.cc_cor_addr_id,w.cc_cee_addr_id,w.ttl_pkgs,w.chrg_wt,wf.wb_bkg_chgd_amt + wf.wb_bkg_chgd_amt_st
      from ops_waybl_fin wf,ops_waybl w
    where wf.id = w.id
       and cre_bill_batch_dtls_id in (select to_number(b.id)
                                        from ops_bill_batch_dtls b,ops_cust_cntr cc
                                       where b.cust_cntr_id = cc.id
                                         and b.bill_batch_id = f1(1)
                                         and b.status_lid = 255
                                         and (((select the_type from variant) = 1
                                               and cc.cust_no in (select param_val
                                                                    from ops_report_req
                                                                   where id = :p_req_id
                                                                     and param_nm = 'CUST_ID'
                                               and cc.ID in (select param_val
                                                               from ops_report_req
                                                              where id = :p_req_id
                                                                and param_nm = 'CUST_CNTR_ID'
                                           or ((select the_type from variant) = 2
                                               and cc.cust_no in (select param_val
                                                                    from ops_report_req
                                                                   where id = :p_req_id
                                                                     and param_nm = 'CUST_ID'
                                           or ((select the_type from variant) = 3
                                               and cc.ID in (select param_val
                                                               from ops_report_req
                                                              where id = :p_req_id
                                                                and param_nm = 'CUST_CNTR_ID'
                                           or ((select the_type from variant) = 4
                                     ) Regards
    Etbin

  • Dynamic UPDATE statement with parameters for column names.

    Hello,
    On this* website I read "The SQL string can contain placeholders for bind arguments, but bind values cannot be used to pass in the names of schema objects (table or column names). You may pass in numeric, date, and string expressions, but not a BOOLEAN or NULL literal value"
    On the other hand, in this Re: execute immediate with dynamic column name update and many other
    posts people use EXECUTE IMMEDIATE to create a dynamic UPDATE statement.
    dynSQL:='UPDATE CO_STAT2 CO SET CO.'||P_ENT_B_G_NAME||' = '||P_ENT_E_G_WE||'
    WHERE ST IN
    (SELECT ST FROM STG_CO_STAT2_TEST CO WHERE
    '||P_ST||' = CO.ST AND
    CO.'||P_ENT_E_G_NAME||' > '||P_ENT_E_G_WE||' AND
    CO.'||P_ENT_B_G_NAME||' < '||P_ENT_E_G_WE||');';
    EXECUTE IMMEDIATE dynSQL ;
    Since this statement is part of a Stored Procedure, I wont see the exact error but just get a ORA-06512.
    The compiling works fine and I use Oracle 11g.
    http://psoug.org/definition/EXECUTE_IMMEDIATE.htm

    OK I extracted from all of your posts so far that I have to use "bind-variables with :"
    From all the other tuorials and forums posts, I assume using the pipe is correct so I added those as well into the script:
    set serveroutput on format wraped;
    DECLARE
    dynSQL VARCHAR2(5000);
    P_ENT_E_G_NAME VARCHAR2 (100) :='test1'; P_ENT_E_G_WE VARCHAR2 (100) :='01.02.2012'; P_ENT_B_G_NAME VARCHAR2 (100) :='01.01.2012';
    P_ST                VARCHAR2 (100) :='32132';
    BEGIN
    dynSQL:= 'UPDATE CO_STAT2 CO SET CO.'||:P_ENT_B_G_NAME||' = '||:P_ENT_E_G_WE||'
                  WHERE ST IN (SELECT ST FROM STG_CO_STAT2_TEST CO WHERE
                  '||:P_ST||'                           = CO.ST                  AND
                  CO.'||:P_ENT_E_G_NAME||'     > '||:P_ENT_E_G_WE||' AND
                  CO.'||:P_ENT_B_G_NAME||'    
    < '||:P_ENT_E_G_WE||')';
    --this is somehow missing after the last < '||:P_ENT_E_G_WE||')';
    dbms_output.enable;
    dbms_output.put(dynSQL);
    --EXECUTE IMMEDIATE dynSQL;    
    END;Problem:I think I figured it out, the dates that I parse into the query need additional '

  • How to retrieve a prepared statement from prepared statement cache?

    Hi All,
    I have created the connection pool during application server startup. The connection pool are getting created successfully. I have also created the prepared statements and stored as part of each connection in the connection pool.
    can anyone please tell me on how do I retrieve a prepared statement from prepared statement cache from a connection object.
    Any pointers to info source will be REALLY appreciated.
    Many Thanks in Advance,
    C R Baradwaj

    Raghuram Bharatwaj C wrote:
    Hi Joe,
    I have created a connection poool in my startup class and created the
    neccessary prepared statements for a each connection. I have 10 prepared
    statements to be created for each connection. I have created all the 10 prepared statements using the loop as mentioned below
    String [] epc_stmts;
    private java.sql.PreparedStatement[] _pstmts;
    if (epc_stmts!= null)
                   _pstmts = new PreparedStatement [len = epc_stmts.length];
                   for (i=0; i<len; i++)
                        _pstmts[i] = db.prepareStatement (epcstmts);
    I have closed the connection after the prepared statements are created.
    Now, How do i access a prepared statement from the connection object.
    Nothing. Are you talking about a WebLogic pool? If so, then therafter,
    whenever your application gets a pool connection, when it calls
    prepareStatement() with the same SQL as you prepared those statements,
    it will get a cached statement. Your array is unnecessary.
    Joe
    >
    Many Thanks in Advance,
    C R Baradwaj

  • Problem - Creating a Dynamic LOV using duplicate value in select statement

    I am trying to create a Dynamic LOV by attempting to follow a pattern similar to the following:
    select shop_name d, shop_id r
    from shops
    order by 1
    However, I want to use the shop_name twice as in the following because I do not have any other unique identifier available such as a shop_id to associate with the shop name:
    select shop_name d, shop_name r
    from shops
    order by 1
    But I get an error where I am not allowed to duplicate the shop_name in the select statement. I read somewhere on this forum where it can be done but I can't find exactly how.
    Can someone tell or show me how to accomplish this?
    Thanks in anticipation for your answer.
    Thanks,
    Ric

    Ric,
    I just tried to do this on APEX 3.0, and it worked just fine with this SQL:
    select ename d, ename r from emp order by 1Perhaps you could put an example on apex.oracle.com or specify the error message that you're getting.
    So as long as you have uniquely aliased both columns, this should not present a problem.
    Thanks,
    - Scott -

  • Using once created prepared statement with different connections in Oracle

    Can I use same statement cash using different connections in Oracle
    For example I have a prepared statement p1. After its using i close connection (return it to the pool)
    Next time I want use p1 statement using another connection.
    Question : When I creat p1 in second time ,is it returned from cash or created as a new statement. And what I should do to use once prepared statement using differend connections.
    Thaks.

    As far as I know a PreparedStatement lives and dies with the Connection that created it. So, you cannot use a PreparedStatement with other Connection instances than the one that created it.
    You will have to recreate the PreparedStatement for each time you open a connection, or use the same PreparedStatement and NOT close the Connection in between. The last suggestion can be risky though, if you never close the connection...
    Jakob Jenkov
    www.jenkov.com

  • Preparing Dynamic SQL statement for inserting in Pro*C

    Hi Friends,
    From quite some time i am struggling writing Dynamic SQL statement for dynamic insert and update in Pro*C.
    Can somebody go through my code and suggest me the rigth way of doing.
    Right now it throws an error saying " Error while updating ORA-00904: invalid column name "
    Please help me.
    Girish.
    int main()
    EXEC SQL BEGIN DECLARE SECTION;
    char *uid ="scott/tiger";
    static char sqlstmt[129];
    struct /* DEPT record */
    int dept_num;
    char dept_name[15];
    char location[14];
    } dept_rec;
    EXEC SQL END DECLARE SECTION;
    EXEC SQL WHENEVER SQLERROR DO sql_error();
    EXEC SQL CONNECT :uid;
    dept_rec.dept_num = 50;
    strcpy(dept_rec.dept_name,"ADMIN");
    strcpy(dept_rec.location,"IN");
    strcpy(sqlstmt,"UPDATE dept set DNAME = dept_rec.dept_name where DEPTNO = dept_rec.dept_num");
    EXEC SQL EXECUTE IMMEDIATE:sqlstmt;
    EXEC SQL COMMIT;
    exit(0);
    void sql_error()
    printf("\nError while updating %s",sqlca.sqlerrm.sqlerrmc);
    EXEC SQL ROLLBACK;
    }

    A bit rusty here but this is how I see it.
    Think of it this way ..
    all Oracle is going to see is:
    UPDATE dept set DNAME = dept_rec.dept_name where DEPTNO = dept_rec.dept_num
    Its NOT going to know what dept_rec.dept_name is or dept_rec.dept_num is ..
    it doesnt go back and fill in those values.
    You need something like
    strcpy(sqlstmt,"UPDATE dept set DNAME = \"");
    strcat(sqlstmt,dept_rec.dept_name);
    strcat(sqlstmt,"\" where DEPTNO = ");
    strcat(sqlstmt,dept_rec.dept_num);
    printf(sqlsmt); # Just to be sure the update statement look right during testing.

  • Dynamically obtain parameter count for a prepared statement

    Hi JDBC Gurus,
    Given a prepared statement, is there a way to figure out the parameter count at runtime? I need this info. to prompt the user for parameter values at the right time from my GUI tool. Any help will be greatly appreciated.

    i don't know of any way to do this put perusing through the API i am wondering what the getMetaData method of PreparedStatement is supposed to do. it says returns the meta data of a ResultSet's columns but i think it could contain info about the parameters for the PreparedStatement. i guess i just don't see why that method is there... anyone?

  • When to use prepared statement in java?

    Hi all,
    If we have query like select * from {tablename} (Here tablename is the variable) then will the use of prepared staement improve the performance? My guess is use of statement in this case is a better option rather than prepared statement as the tablename may change for every other query.I think are not useful if tablename changes.They are useful only when the where clause has dynamic values.

    cantor wrote:
    Are you sure that your approach is possible? The next example causes exception for me.
    PreparedStatement ps = conn.prepareStatement("select * from ?");
    ps.setString(1, "TABLE_NAME");
    ps.executeQuery();
    I didn't say that he should solve it in that way. He should create one prepared statement like this "select a, b, c from tablename1" and another prepared statement when he wants to execute "select d, e, f from tablename2"
    >
    And as I understand, this code will not improve perfomance (and even will not work). As I said it can.
    Prepared statements make possible usage compiled queries inside DB. When DB gets prepared statement call, it need to parse it only once. And it can collect some statistic to improve execution plan. But when table name is not specified, this approach will not work.Yes it might. There are database drivers that can cache prepared statements and it's isn't likely that he executes that query on more than e.g. 20 tables?
    The database can also cache compiled statements in a cache.
    Kaj

  • Using partition in prepared statement

    Hello,
    I am connecting to an oracle 9i database and write a prepared statement like
    String query = "SELECT * FROM ADM.TABLE1 PARTITION (TABLE1_?)";
    PreparedStatement pstmt = dbConnection.prepareStatement(query);
    pstmt.setString(1, "20" + callDate); // Partitions are like TABLE1_20030605
    ResultSet rs = pstmt.executeQuery();
    I get this error ORA-00933: SQL command not properly ended
    Any ideas if i am substituting the value correctly or if this is the right way to use prepared statement ?

    It is the wrong way to use a prepared statement.
    You will need to create the string dynamically.

  • Passing values for a prepared statement encounters problem

    I have a query which runs fine when executed from sqlplus
    SELECT SYSDATE + (INTERVAL '10' MINUTE) FROM dual;
    The same query when run using a java statement also works well.
    when I use a Prepared statement like
    String sql = SELECT SYSDATE + (INTERVAL ? MINUTE) FROM dual;
    PreparedStatement ps = this.getPreparedStatement(sql.toString());
    ps.setString(1, "10");
    and execute I get the following exception
    ORA-00920: invalid relational operator
    I tried another way which also gives me a similar exception
    String timeout = "10";
    SELECT SYSDATE + (INTERVAL" + timeout + "MINUTE) FROM dual;
    Can anybody tell me why the problem happens. Is anything wrong in passing values dynamically for an 'interval' function in oracle?

    asokan_srini wrote:
    Yes friends
    Thanks for the reply. It worked out this way as u said
    sql.append("SELECT SYSDATE + (INTERVAL ");
    sql.append("'" + Integer.parseInt(timeout) + "' MINUTE) FROM dual");
    Mr.masijade said.
    First of all, there is no reason to do this command, really, but okay.
         There may be scenarios like this to use the command
              select * from mytable where (systimestamp - lastUpdateTimestamp) > Interval '10' Minute
    Is there any other better way to get all records updated before a certain timestamp?Use Timestamp to create a timestamp and PreparedStatement's setTimestamp(), maybe?

  • Prepared Statement with SQL 'IN' Clause

    Hi,
    I am trying to write a JDBC SQL call to a database using a prepared statement, the call looks something like:
    select *
    from table
    where field in (?, ? ,?)
    this thing is that i don't know how many 'IN' parameters are needed until runtime (they come from a List), so is there an easy way of dealing with this, I haven't been able to find any information on this problem anywhere?

    >
    Hmmm...more expensive than say doing a query on on 2 billion rows with no index?
    More expensive than doing a cross server join?
    More expensive than doing a restore?
    I knew that someone would point this out. :)
    I just tried to exaggerate the importance of cursor sharing. This is one of the most important topic in DBMS world, but quite often ignored by JAVA world. I hope that you understand my good intention.
    >
    2. Insert data corresponding to bind variable to "T". Interesting idea. Please provide the algorithm for that. The only ones I can come up with
    1. Involved creating a "dynamic" SQL for the insert
    2. Doing multiple cross network inserts.
    The first of course is exactly what you said your solution prevented. The second will be more expensive than sending a single dynamically created select.Hopefully, this is not just an "interesting" idea, but very common technique in DBMS. Actually one of the common techniques. There are couple of ways to handle this kind(variable number of bind variables in "IN" clause) of problem.
    What i commented was that the simplest one. It's like this:
    (based on Oracle)
    SQL> create global temporary table bind_temp(value int);
    PreparedStatement stmt = con.prepareStatement("INSERT INTO bid_temp VALUES(?)");
    for(...) {
         stmt.setInt(1, aValue)
         stmt.addBatch();
    stmt.executeBatch();
    Statement stmt2 = con.executeQuery("SELECT * FROM target_table WHERE id IN (bind_temp)");
    ...Doesn't it look pretty? Pretty for both Java developers and DBAs.
    By virtue of the mechanism of batch processing, the total DBMS call is just twice and you need just 2 completely sharable SQL statements.
    (Hopefully you might understand that Oracle global temporary table is just session scope and we don't need them to be stored permanently)
    Above pattern is quite beneficial than these pattern of queries.
    SELECT * FROM target_table WHERE id IN (?)
    SELECT * FROM target_table WHERE id IN (?,?)
    SELECT * FROM target_table WHERE id IN (?,?,?)
    SELECT * FROM target_table WHERE id IN (?,?,?,?,.......,?)
    If you have large quantity of above patterns of queries, you should note that there are another bunch of better techniques. I noted just one of them.
    Hope this clairfies my point.

  • Can any body Help me to prepare statement

    I want to provide dynamic table name for preparestatement that i just pass table name every time and it pass me total number in that table.
    I create this prepare statement
    PreparedStatement prepStmt=conn_.prepareStatement("select count(*) Total from ?");
    prepStmt.setString(1,"new");
    but it is giving error
    [JDBC SQL Server Driver] Line 1: Incorrect syntax near 'new'.
    Any body can help me??
    I will appreciate.

    In PreparedStatement, the setString method adds quotes at the start and at the end of your String.
    So your request :
    select count(*) Total from ?
    is interpreted :
    select count(*) Total from 'new'
    One possible solution is to pass your tablename parameter directly in the precompiled request :
    String myTableName = "new";
    PreparedStatement prepStmt=conn_.prepareStatement("select count(*) Total from "+myTableName);
    In your database, you will store as many precompiled Statement as you will call this method with different parameters.
    Hope it helps !

Maybe you are looking for

  • How to Save Camera Calibration and Lens Correction in Camera raw 6.1

    I downloaded and installed the Camera Raw 6.1 release candidate.  I open an image and set the camera calibration and the lens correction to auto for Nikon.  I save these settings as new Camera raw defaults, but when I open other images, the changes w

  • ITUNES HELP

    Hello everybody i need help i have a windows 7 dell laptop and itunes wont open when i click it, it comes up with this nonifaction 'the folder itunes is locked to disc or you dont have write permissions' can someone plz help!

  • Need help in re-architecting an environment

    We have 6 Solaris servers running multiple instances of BEA WLS 8.1SP3. We have about 30 instances spread out over these 6 servers. Each app instance has it's own admin and managed server(Don't ask me why we have a seperate admin server for each app

  • Runtime Error C++ etc..

    Hi. Frustrated. Ive been using Premier Elements 11 for sometime now. Maybe 6 months. All has been good. Loaded the program onto my new computer, all has been better. http://www.toshiba.com/us/computers/laptops/qosmio/X70/X75-A7298?src=ANEM&cm_mmc=SF_

  • Expose animation lag & Dashboard ripple gone after 10.6 on Macbook Pro '08

    I upgraded a Macbook Pro 2008 model (MacBookPro4,1) to OS X 10.6.2 (Snow Leopard), and various animation effects across the OS started having issues. 1.) Expose animation of windows coming into place is now laggy. 2.) Dashboard's water ripple effect