Using SYSDATE in a PreparedStatement

I feel sure this must have done already, but ....
I need to use a PreparedStatement to insert rows. The table has a DATE column and I want to use the SYSDATE value.
I've tried using setString("SYSDATE") and setObject("SYSDATE") but I'm getting ORA-01585 errors each time.
What's the "official" mechanism for doing this?
I can't use a Date object from the client because I can't be sure the clent and server clocks will be in sync.
I also can't do SELECT SYSDATE FROM DUAL because the PreparedStatement is batched and I want the timestamp from
when the row actually hits the DB.
Any suggestions welcome.
Thanks in advance.
Andy

Hi Andy,
When we do pstmt.setString("SYSDATE"), behind the screen it goes as 'SYSDATE' (since its string) and will not be appended to the query as SYSDATE.
So append the SYSDATE to the query while preparing your statement.
String insertsql = "insert into emp (empid, name, dept , joindate) values (?, ?, ?, SYSDATE ) ";
PreparedStatement pstmt = conn.prepareStatement(inssql);
pstmt.setInt(1, 123);
pstmt.setString(2, "my name");
pstmt.setString(3, "my dept" );
pstmt.executeUpdate();
Regards
Elango.

Similar Messages

  • How to use SYSDATE as a default value of a bind variable in a query report?

    Hi,
    I want to use SYSDATE as default value for a bind variable in Query based report.
    I don't see any way to do it, someone helps?
    Thanks a lot.
    Paulo.

    You can aslo use #sysdate directly.
    Hi,
    The way I'm doing in my report is, I have a database function (f_ret_sysdate) with the following code
    create function f_ret_sysdate return varchar2
    begin
    return to_char(sysdate,'mm/dd/yyyy');
    end;
    Now, in the 'Customization Form Display Options' section of the report I'm calling this function as #f_ret_sysdate in the default value field of corresponding bind variable to display SYSDATE with the format.
    Hope this helps!...
    -Krishnamurthy

  • Count of a query in Unix environment and use sysdate

    hi,
    i have a code below and i want this to be used in Unix env and i need to use sysdate where i hard coded the date but the time should remain as it is.
    select count(type),type from ebizp.bchistevent
    where (type = 'com.avolent.apps.event.LoginEvent' or type = 'com.avolent.apps.event.LogoutEvent')
    and(to_char(createdt, 'dd/mm/yy hh24:mi s') between '28/01/13 08:00:00' and '28/01/13 09:00:00')
    AND ( bucket = to_char(sysdate-1, 'YYYYMM') OR bucket = to_char(sysdate, 'YYYYMM') OR bucket = 0)
    group by type
    like it should be between 'sysdate 08:00:00' and 'sysdate 09:00:00')
    please suggest.

    Dates should be compared with dates values. Don't use to_char to compare date values.
    And dont use "TYPE" as a column name - it is a reserved key word..
    select count(type), type
    from ebizp.bchistevent
    where (
        type = 'com.avolent.apps.event.LoginEvent'
        or type     = 'com.avolent.apps.event.LogoutEvent'
    AND createdt BETWEEN trunc(sysdate)+(8/24) AND trunc(sysdate)+(9/24)
    and (
      bucket = to_char(sysdate-1, 'YYYYMM')
      or bucket    = to_char(sysdate, 'YYYYMM')
      or bucket    = 0
    GROUP BY type;And you can simplify the query
    select count(type), type
    from ebizp.bchistevent
    where type in
        ('com.avolent.apps.event.LoginEvent','com.avolent.apps.event.LogoutEvent')
    AND createdt BETWEEN trunc(sysdate)+(8/24) AND trunc(sysdate)+(9/24)
    and bucket in
         (to_char(sysdate-1, 'YYYYMM'),to_char(sysdate, 'YYYYMM'),'0')
    GROUP BY type;Edited by: jeneesh on Feb 19, 2013 2:42 PM

  • Using 'SYSDATE' function in ACCESS 2000?

    'SYSDATE' function is not working in ACCESS 2000 , is there any other
    alternative function available in access.
    I use a select statement using SYSDATE, but it did not work.

    I found it already.
    use the now() function.

  • Using SYSDATE in RMAN script

    Hi
    Each night I move an RMAN backup from a PROD server to a test server.
    Then using RMAN script with NOCATALOG, I restore/recover the database on the test server as show below:
    RUN{
    ALLOCATE CHANNEL dev1 DEVICE TYPE DISK;
    STARTUP NOMOUNT;
    RESTORE CONTROLFILE from AUTOBACKUP;
    SHUTDOWN;
    STARTUP FORCE MOUNT;
    RESTORE DATABASE;
    RECOVER DATABASE;
    ALTER DATABASE OPEN RESETLOGS;
    Of course the script fails at the "RECOVER DATABASE" command because it runs out of ARCH logs to apply at some point and therefore never gets to the final command of DATABASE OPEN. I would like to change that line to something like:
    RECOVER DATABASE UNTIL TIME 'SYSDATE:02:45:00';
    The above fails with an RMAN error of "expected number".
    Of course I could use SET UNTIL TIME "to_date('SYSDATE 02:45:00','DD-MON-YYYY HH24:MI:SS')"; although I have the same problem, i.e., getting RMAN to accept SYSDATE as the date portion of the point in time recovery.
    Oddly, from an RMAN prompt and within brackets, I can issue the following command successfully:
    RMAN {
    set until time "to_date('SYSDATE 02:45:00','DD-MON-YYYY HH24:MI:SS')";
    command completed successfully
    So my question is, how can I use SYSDATE in an RMAN point in time recovery and have sysdate represent the current date, either in the RECOVER DATABASE line or the SET UNTIL TIME line?
    Thanks.

    user522620 wrote:
    Hi
    Each night I move an RMAN backup from a PROD server to a test server.
    Then using RMAN script with NOCATALOG, I restore/recover the database on the test server as show below:
    RUN{
    ALLOCATE CHANNEL dev1 DEVICE TYPE DISK;
    STARTUP NOMOUNT;
    RESTORE CONTROLFILE from AUTOBACKUP;
    SHUTDOWN;
    STARTUP FORCE MOUNT;
    RESTORE DATABASE;
    RECOVER DATABASE;
    ALTER DATABASE OPEN RESETLOGS;
    So my question is, how can I use SYSDATE in an RMAN point in time recovery and have sysdate represent the current date, either in the RECOVER DATABASE line or the SET UNTIL TIME line?
    Thanks.
    Given:
    SQL> alter session set NLS_DATE_FORMAT='DD-MON-YYYY HH24:MI:SS';
    SQL> select to_char(trunc(sysdate)+(2/24)+(45/1440),'dd-mon-yyyy hh24:mi') from
    dual;
    TO_CHAR(TRUNC(SYS
    25-JUN-2012 02:45:00
    Use this (uses to_date)
    RUN{
    set until time "to_date(trunc(sysdate)+(2/24)+(45/1440),'DD-MON-YYYY HH24:MI:SS')";
    ALLOCATE CHANNEL dev1 DEVICE TYPE DISK;
    STARTUP NOMOUNT;
    RESTORE CONTROLFILE from AUTOBACKUP;
    SHUTDOWN;
    STARTUP FORCE MOUNT;
    RESTORE DATABASE;
    RECOVER DATABASE;
    ALTER DATABASE OPEN RESETLOGS;
    ## if that command fails, it will fall to the next command as the run blocks are autonomous.
    RUN{
    ALTER DATABASE OPEN RESETLOGS;
    }

  • Can I use SYSDATE in the WHERE clause to limit the date range of a query

    Hi,
    Basicaly the subject title(Can I use SYSDATE in the WHERE clause to limit the date range of a query) is my question.
    Is this possible and if it is how can I use it. Do I need to join the table to DUAL?
    Thanks in advance.
    Stelios

    As previous poster said, no data is null value, no value. If you want something, you have nvl function to replace null value by an other more significative value in your query.<br>
    <br>
    Nicolas.

  • Using sysdate in a ejb 3.0 named query

    Hello,
    Giving the following ejb 3 Named query:
    @NamedQuery(name = "DcaMessage.findNew", query = "select o from DcaMessage o where o.nbAvisEmis<1 or (o.indMsgConsulte=0 and sysdate-o.dtDernierAvis>:nbJours)")
    The result is:
    Exception [TOPLINK-8004] (Oracle TopLink Essentials - 2006.8 (Build 060829)): oracle.toplink.essentials.exceptions.EJBQLException
    Exception Description: A parsing problem was encountered resolving the alias - [sysdate].
    How do I use sysdate (or any other element) to compute the number of days between now and the date defined in dtDernierAvis?
    Thanks

    Hi,
    According to the EJB 3.0 specification, there are three date and time functions that can be used in EQL:
    functions_returning_datetime:=
    CURRENT_DATE |
    CURRENT_TIME |
    CURRENT_TIMESTAMP
    The datetime functions return the value of current date, time, and timestamp on the database server.
    I suppose your query should look like this
    @NamedQuery(name = "DcaMessage.findNew", query = "select o from DcaMessage o where o.nbAvisEmis<1 or (o.indMsgConsulte=0 and CURRENT_DATE-o.dtDernierAvis>:nbJours)")
    I never used these three functions myself, but it should be something like that.
    HTH, Wouter van Reeven

  • How can I spool file in SQL*Plus using sysdate as filename?

    Dear Oracle Experts,
    Would you help me to solve following problem?
    I want spool a file in SQL*Plus but using sysdate as filename.
    e.g. today is 30-Nov-1999
    then the filename is 19991130.lst
    tommorrow is 1-Dec-1999
    then the filename is 19991201.lst
    My e-mail address is [email protected]
    Thanks!!!
    Tony Sit
    null

    Tony Sit (guest) wrote:
    : Dear Oracle Experts,
    : Would you help me to solve following problem?
    : I want spool a file in SQL*Plus but using sysdate as filename.
    : e.g. today is 30-Nov-1999
    : then the filename is 19991130.lst
    : tommorrow is 1-Dec-1999
    : then the filename is 19991201.lst
    : My e-mail address is [email protected]
    : Thanks!!!
    : Tony Sit
    Tony, hi!
    Let you test this way:
    set ECHO OFF
    set TERMOUT OFF
    set FEEDBACK OFF
    set VERIFY OFF
    SET PAGESIZE 0
    SET LINESIZE 80
    SET HEADING OFF
    spool setout.sql
    SELECT 'SPOOL '

  • Can I use SYSDATE for retrieving data?

    Hi all,
    I'm working on MS Windows XP SP3 and my date format in oracle is '01-DEC-2008'. Now I have created a table with DATE type column then I insert a record in it using the SYSDATE like this
    INSERT INTO Birthdays (ID, Name, BDate)
    VALUES (1, 'Zikas', SYSDATE)Then when I try to retrieve this record after I have inserted in (in the same day I mean) by the Select statement
    SELECT *
    FROM Birthdays
    WHERE BDate = SYSDATEthere is no records retrieved. So how to insert a record with SYSDATE and then retrieve it also using SYSDATE?
    Thanks in advance :)

    Zikas,
    Sysdate gives you current data and time and you saved your record in past (like 1 minute ago or 1 hr go), though date are same but time is different as mentioned in the previous post. Take a look this example and make sure you commit after insert.
    CREATE TABLE birthday (
       id NUMBER,
       name VARCHAR2 (30),
       bday DATE
    INSERT INTO Birthday (ID, Name, BDay)
    VALUES (1, 'Zikas', SYSDATE)
    commit;
    SQL> select * from birthday where trunc(bday)=trunc(sysdate);
            ID NAME                           BDAY
             1 Zikas                          28-DEC-08Regards

  • How do I use Sql hints in PreparedStatement?

    Hi,
    I am trying to use a sql query which uses Oracle hints to optimize the query. I am using the ojdbc drivers from Oracle. I am using the PreparedStatement (Java 1.4) to execute this query, but it returns an empty resultset. If I remove the hint, then the query works fine using the PreparedStatement. Does anyone know how to make sql hints work using preparedstatement. I tried it with Statement object and that works (ie. the hint works and returns rows as expected).
    The query is as follows:
    select /*+ ordered
    use_nl(ri ma)
    count(*),
    ma.columnName
    from table1 ri,
    table2 ma
    where ma.columnName2 = ri.columnName2
    and ma.column3 = 1
    and ri.column4 = 66
    group by ma.columnName
    I tried escaping the /*+ but that also didn't work. Any help would be appreciated.
    Thanks in advance,
    Parag

    Must be an old database.
    Presumably you tried it in sqlplus and it worked both ways. If not then nothing you do will make it work in java.
    Other than that my quess would be that it has nothing to do with the select.
    Some possibilities.
    1. You are eating exceptions.
    2. You are not running the code that you think you are.

  • Using "where in" for PreparedStatement

    Hi,
    I need to make a query to MySql database with "WHERE id IN (int,int,int)". number of integers in the query is 1-N
    I can't find how i can do this. if i set the PreparesStatement with "WHERE id IN (?)" and try ps.setString(1,parameters) where parameters is for example "1,2,3,4", the query returns only rows with id 1 (since i use setString the query will be "WHERE id IN ('1,2,3,4')")
    could someone tell me what method i should use to get correct rows, or if it's impossible to do so.
    if it's impossible would it be faster to set the PreparedStatement to "WHERE id IN (?,?,?,?,?,?,?,?,?,?)" and when i need to look for fewer than 10 different ids (when i know 10 is the max), i'll just make it to "WHERE id IN (1,2,3,4,4,4,4,4,4,4) ?
    is it slower to make nonprepared statement than bigger where in?

    This has got nothing to do with PreparedStatement Support.
    You must be setting the 1,2,3,4 as rs.getString() within the code.
    B4 doing that do this at mysql prompt
    select * from some_table where id in (1,2,3,4)
    and
    select * from some_table where id in ('1,2,3,4');
    The results are different and by doing setString you are actually sending second statement in my above example. That 's why it doesn't work. The best thing to do is
    conn.prepareStatement("select * from some_table where id in (?,?,?,?));
    pstmt.setInt(1,1);
    pstmt.setInt(2,2);
    pstmt.setInt(3,3);
    pstmt.setInt(4,4);
    and this will work very well

  • How to use LIKE operator with PreparedStatement

    Hi, I need to execute a query with the LIKE operator, but using a PreparedStatement. Can I do this, and if so what must my SQL look like with the wildcard characters '%' or '_'?
    normal PS example: conn.prepareStatement("select * from mytable where name like ?");
    If I try: conn.prepareStatement("select * from mytable where name like ?%");
    I get: ORA-00911: invalid character
    If I try: conn.prepareStatement("select * from mytable where name like '?%'");
    I get: ORA-01006: bind variable does not exist
    I must use a PreparedStatement, as my variable may contain illegal characters (like '), and using PreparedStatement.setString(1, var) will automatically escape it for me.
    I could also use a normal Statement, but I need to escape my var ... is there a utility that will safely escape a String for an Oracle VARCHAR2??
    Thanks in advance,
    Stu Miller

    Hmm, it seems you are right...
    when my variable contains a '%' symbol, the PreparedStatement will NOT escape it, and thus it is treated like a wildcard. Therefore, I can just do
    pstmt.setString(1, var+"%");
    But, that may return more results than I'm asking for, as when 'var' contains a '%' symbol it is taken as a wildcard too.
    I need each character in my variable to be taken literally, and only add a wildcard at the end. Basically, I need a STARTSWITH operator ;-)
    It seems to me that escaping the sensitive characters in a String (which will differ depending on which operator is used), should be possible. I could write this, but I was hoping Oracle had already done it for me in some utility class.

  • Using SYSDATE in Pre-Defined View Criteria ADF BC

    I’m trying to setup a View Criteria to find records between two dates. So I create a View Criteria and Select my date field from the table and then choose the “Between” operator and then my operand is a Bind Variable. Then in my Bind variables I have SYSDATE and SYSDATE-7. So in my view.xml I have the following:
    <Variable
    Name="SystemDate"
    Kind="viewcriteria"
    Type="java.sql.Date">
    <TransientExpression><![CDATA[SYSDATE]]></TransientExpression>
    </Variable>
    <Variable
    Name="Bind_SystemDateMinusSeven"
    Kind="viewcriteria"
    Type="java.sql.Date">
    <TransientExpression><![CDATA[SYSDATE-7]]></TransientExpression>
    </Variable>
    However, when I try to run this View Criteria (using on an af:query component), I get the following error.
    Messages for this page are listed below.
    Error     
    Unexpected exception caught: java.lang.reflect.UndeclaredThrowableException, msg=null
    Error     
    Name SYSDATE not found in the given object: ViewRow [oracle.jbo.Key[877 ]
    Does anyone know how to do this using ADF BC and View Criterias? I've tried making my bind variables Strings and this doesn't work either. I basically want a predefined query that finds records within a specific week given the system date. Any ideas on how to make this work? Thanks.

    You can achieve SYSDATE in ADF BC View Criteria using IsSqlFragment="true".
    Below is the VO source code snippet for the same.
    <ViewCriteriaItemValue
                Name="ViewObjCriteria_ViewObjSubCriteria1_vcrow40_HireDate_vcval0"
                Value="sysdate-350" IsSqlFragment="true"/>
              <ViewCriteriaItemValue
                Name="ViewObjCriteria_ViewObjSubCriteria1_vcrow40_HireDate_vcval1"
                Value="sysdate" IsSqlFragment="true"/>
    </ViewCriteriaItem>

  • No querryresult because of using sysdate

    Something is wrong with my date format. I receive no results in the querry after I use the following code in trigger key-menu
    begin
    if Get_Item_Property(:system.cursor_item, DATATYPE)='DATE' then Copy(trunc(sysdate) , :System.Cursor_Item);
    end if;
    end;
    wenn I write the date into the field by hand without the a.m. trigger I receive datas from the querry. something is wrong with my dateformat, but what?
    mfg
    robert

    sorry, it does not work. before starting the querry the following trigger is done:
    if :system.tab_new_page='FALSCH_VERLADEN' then
    go_block('K_FALSCHGELADEN_VW');
    clear_block(no_validate);
    set_block_property(:system.current_block, default_where, 'Lieferdatum>=:AB2.von AND
    Lieferdatum<=:AB2.BIS');
         go_block('AB2');
    clear_block(no_validate);
    end if;
    ENTER_QUERY;
    after that I press f5 to do trigger key-menu to set the query-date:
    if Get_Item_Property(:system.cursor_item, DATATYPE)='DATE' then
         Copy(TO_CHAR(trunc(sysdate), 'DD.MM.RR') , :System.Cursor_Item);
    end if;
    the same trigger is used for field ab2.von and ab2.bis
    then I press button for execute querry. the following trigger is done:
    if :system.tab_new_page='FALSCH_VERLADEN' then
    go_block('K_FALSCHGELADEN_VW');
    END IF;
    EXECUTE_QUERY;
    maybe that helps. I have no Idea why it is wrong. if I use the following code in the key-menu trigger for :ab2.von and :ab2.bis it works:
         if Get_Item_Property(:system.cursor_item, DATATYPE)='DATE' then
         :ab2.bis := sysdate;
    end if;
    any idea??
    robert

  • ODI Variable using SYSDATE - Issues comparing against EBS last_update_date

    Hello All,
    I followed the directions in the Oracle blog "Using Variables in ODI: The Timestamp Example". I created the variables and the package. My interface is trying to load incremental data from the source GL_JE_BATCHES table to my target table. I am comparing the last_update_date field in the GL_JE_BATCHES table to the LastUpdate variable. Using the standard variable build per the blog [Select sysdate from dual] I am receiving all kinds of errors. When I view the value in the variable I see 2009-12-23 [no quotes]. I have tried all kinds of to_char and to_date conversions on both the variable and the last_update_date fields. No matter what I've tried and Ican't make the variable work. Now I'm up against a deadline and I'm reaching out for some help! Hopefully someone else is working during the holidays!
    Thanks!
    Cheryl

    Thanks for taking the time to answer during the holidays!
    I am using an alphanumeric variable type. A few additional details:
    -- when I execute a query against the GL_JE_BATCHES table - WHERE last_update_date >= sysdate --- this query works
    -- same table - WHERE last_update_date = '10-Oct-2009' --- this query works
    -- same table - WHERE last_update_date = 10/10/2009 -- errors out with the 'expecting a date and received a number' error code.
    -- same table - WHERE last_update_date = 10-Oct-2009 -- errors out the 'DEC' is not a valid month.
    The list goes on and on. Seems like the only format, other than sysdate, that the source accepts = '10-Oct-2009'. So far I have not been able to get the variable to return that value. Using to_char I can get the variable 'value' to = 10-Oct-2009 but without the quotes.
    Your continued support and assistance is greatly appreciated!

Maybe you are looking for