SQL query throwing Exception.

Hi,
i am facing a problem while using the date as search criteria. In the JDO class the field type is of java.util.Date. The search is working in the local environment whose local date settings as M/d/YYYY(windows 2003 , english version).The search is not working in the chines OS environment , where the local date setting is YYYY-M-d. In the chinese enviroment , if we alter the session NLS settings in toad, we could able to execute the query.
we are using kodo-2.5.8
SELECT t0.JDO_ID, t0.JDO_CLASS, t0.BAD_NAMES, t0.CONCAT_NAME, t0.DDATE, t0.FIRST_NAME, t0.LAST_NAME, t0.MAX_SCN, t0.NAME,
t0.NATURALID, t0.PARTYID, t0.PHONE, t0.ROLE FROM PARTY_VBO t0 WHERE (t0.ROLE LIKE '%ICR%' AND t0.DDATE = '17-APR-1974' AND ROWNUM <= 25) AND
t0.JDO_CLASS = 2 ORDER BY t0.PARTYID ASC)
This Query is throwing ORA-01843.
From where the session opened by the java in oracle will take the data format?

Plaese help.
One of my sql query is throwing exception during
execution. I do not know which one (there are several
of them). Is there a way to display or extract the
last query from SQLException class.
Any help will be highly appreciated.
Thanks,
Indrasish.No there is not. You should do some debugging, such as logging something like: "Executing query: SELECT blahblahblah" - then execute the query, then log something like: "Query completed". Then find in your log which one didn't complete.

Similar Messages

  • SQL Query and Exception ORA-01722

    Hi,
    I have a table called t_lookup which has three columns Lookup_Value, Description and Lookup_Type all of them are varchar2 type. If I execute the below query, its working fine
    SELECT *
    FROM (SELECT Lookup_Value
    *,To_Number(Description) Dd*
    FROM t_Lookup
    WHERE Lookup_Type = 'CALENDAR') Tab ;
    Here is the result
    Lookup_Value .............. Dd
    January....................... 1
    February..................... 2
    March......................... 3
    April........................... 4
    May........................... 5
    June.......................... 6
    July........................... 7
    August....................... 8
    September................... 9
    October...................... 10
    November................... 11
    December................... 12
    But when i execute
    SELECT *
    FROM (SELECT Lookup_Value
    *,To_Number(Description) Dd*
    FROM t_Lookup
    WHERE Lookup_Type = 'CALENDAR') Tab
    AND Dd = 9;
    then it is throwing ORA exception
    ORA-01722: invalid number
    Can any one help me on this in order to understand the root cause of this problem? Oracle server I am using is "Oracle9i Release 9.2.0.8.0" .
    Thanks

    I'm assuming that it is intended that certain descriptions will have non-numeric data in them, right?
    Assuming that is the case, the success or failure of the query will depend on how the optimizer happens to choose to execute your query. If it happens to run the TO_NUMBER function before it filters out a row with non-numeric data, you'll get an error. If it happens to run the TO_NUMBER after filtering out all the rows with non-numeric data, the query will be successful. Given that query plans are subject to change, particularly when you eventually upgrade, you probably don't want to just find a SQL query that works, you'll need to ensure that either the query plan never changes or that the query is formulated in such a way that it will never fail.
    My first thought would be whether you really need to store numeric data in a VARCHAR2 field in the first place. I'm guessing this is some sort of generic lookup table (which cause a raft of issues, this being one). Can you at least store string, date, and number data in separate columns?
    Barring that, can you create your own PL/SQL function that converts a string to a number and catches the exception?
    CREATE OR REPLACE FUNCTION my_to_number( p_arg IN varchar2 )
      RETURN NUMBER
    IS
      l_num NUMBER;
    BEGIN
      l_num := to_number( p_arg );
      RETURN l_num;
    EXCEPTION
      WHEN others THEN
        RETURN NULL;
    END;That will ensure that the query will be successful regardless of the plan. Note that you would probably want to catch just the ORA-01722 error, not OTHERS, in your real code-- this is just a sample.
    Barring that, you'll need to do something to enforce stability in the query plan. A stored outline that forces this query to use the query plan that doesn't generate an error.
    Justin

  • Second call of an SQL query throws a syntax error?

    Private Sub RefreshDataSet()
    Dim strSQL As String = DataAdapter1.SelectCommand.CommandText
    Try
    DataSet1.Clear()
    DataAdapter1.SelectCommand.CommandText() = Trim(strSQL & " WHERE BadgeID = " & strEmployeeBadge)
    DataAdapter1.Fill(DataSet1)
    Catch ex As Exception
    MsgBox(ex.Message)
    End Try
    End Sub
    When I call the above procedure, the sub does work correctly and I get the expected results / records in the dataset.  But, when I call the Sub again (to refresh the dataset) it gives me an "incorrect syntax" error.
    I'm not sure why it is doing this.  Any suggestions or ideas?

    Youjun,
    It's very frustrating when you keep asking if the code is the same, or if I have tested the code.  I've said that I debugged.. I've said I have tested the code.  Your continuing to ask me this is pointless, rude, and only serves to make YOU look
    stupid.  I'm sorry if that is rude, but please stop asking me!
    To respond:
    I supposed that the original DataAdapter1.SelectCommand.CommandText is "select * from table1"
    -Yes, the base command is similar to this, except that I call each database field, not using the *.
    1) When you run it the first time, the DataAdapter1.SelectCommand.CommandText will be "select * from table1 WHERE BadgeID ='123'".
    -Yes, I append 'WHERE BadgeID = XXX' to the query, the first and
    each subsequent time.  Again, I said that the code/call/syntax DOES NOT CHANGE.  It is the
    same every time.
    2) Then you changed the strEmployeeBadge, I supposed that is '234'
    -NO!  I do NOT change the code!!  I'm sorry, but what part of 'the query is
    exactly the same' is unclear?
    3) when you run it next time, the DataAdapter1.SelectCommand.CommandText will change to "select * from table1 WHERE BadgeID ='123'
    WHERE BadgeID = '234'"
    -NO!  I have specifically tested for this
    and as stated, the SQL syntax does not change!
    So it 'syntax' fail will pop out when second call.
    -NO, your assumptions are INCORRECT.
    I suggest you recording the commandText when first change the DataAdapter1.
    I write a testing program for you.
    -Your 'testing program' is for all purposes, the same exact code as what I used.  There is no difference.  
    Now, as also stated before, I have several other instances
    where I use the same 'technique' to amend the base SQL queries of the DataAdapter.  Each of these other instances work fine, and I use them to 'refresh' my DataSet information several times throughout the running of my program.  Just for some
    reason, this time, it does not work.  I don't know why and was hoping someone else had found the same/similar issue and also found a resolution.  The DataAdapter is configured the same as the others, the code is the same as well.  I will just
    have to find a work around, or other way to do what I want I guess.
    Lastly, yes, I set strSQL in the subroutine because I want that variable to be gone at the end of the procedure.  It recalls, then sets the syntax, every time the Sub is called on purpose.  I do not want strSQL to be 'global', which by the way,
    according to Microsoft documentation I have read, is no longer possible.  Global variables are 'technically' not used/recognized anymore.  If this has changed, then I stand corrected.
    Thank you for responding, I will just find another solution I guess.

  • SQL query throws not understandable error

    Hi everybody,
    I am suffering from an issue where I query Oracle database 11g with this query:
    SELECT AUDIT_EVENT.EVENT_ID, USER_NAME, START_TIMESTAMP, AUDIT_EVENT.DURATION, AUDIT_EVENT.EVENT_TYPE_ID, AUDIT_EVENT.SERVER_CUID, OBJECT_CUID, OBJECT_TYPE, ERROR_CODE, OBJECT_ID, DETAIL_ID, AUDIT_DETAIL.SERVER_CUID, AUDIT_DETAIL.DETAIL_TYPE_ID, DETAIL_TYPE_DESCRIPTION, EVENT_TYPE.EVENT_TYPE_DESCRIPTION, SUBSTR(DETAIL_TEXT,0,200) as DETAIL_TEXT FROM (audit_detail join detail_type on audit_detail.detail_type_id=detail_type.detail_type_id) join (audit_event join event_type on audit_event.event_type_id=event_type.event_type_id) on audit_event.event_id=audit_detail.event_id WHERE to_char(START_TIMESTAMP,'YYYYMMDD') > '20110307' AND to_char(START_TIMESTAMP,'YYYYMMDD')<='20110309' ORDER BY START_TIMESTAMP
    which throws this error:
    ORA-01652: unable to extend temp segment by 128 in tablespace TEMP
    01652. 00000 - "unable to extend temp segment by %s in tablespace %s"
    *Cause:    Failed to allocate an extent of the required number of blocks for
    a temporary segment in the tablespace indicated.
    *Action:   Use ALTER TABLESPACE ADD DATAFILE statement to add one or more
    files to the tablespace indicated.
    Can anybody explain why this can happen? Are we somehow limited with temporary space or whatever? Because when I put the same query withou condition placed after WHERE clause it seems to work correctly...
    Appreciate any help..
    Thank You
    Miro

    Temp space can be used for SORTS and HASH joins, for example.
    See documentation for further details:
    http://download.oracle.com/docs/cd/E11882_01/server.112/e17120/tspaces002.htm#i1013552
    http://download.oracle.com/docs/cd/E11882_01/server.112/e16638/memory.htm#PFGRF01401
    Please review the execution plans for both queries that you mention.
    e.g.
    explain plan for...
    select * from table(dbms_xplan.display);The output of dbms_xplan should display expected/estimated temp space usage.
    Please see the following thread for more detail:
    How to post a SQL tuning request - HOW TO: Post a SQL statement tuning request - template posting
    I see that you using a TO_CHAR on your START_TIMESTAMP column.
    This is a classic way of preventing index usage which may lead to inefficient plans which might cause unexpected temp space usage.
    See execution plans for further detail.
    If START_TIMESTAMP is indexed, then doing the following may result in a more efficient plan which might lead to reduced temp space usage, any sort operation ing might even be eliminated:
    WHERE START_TIMESTAMP >= TO_DATE('20110307','YYYYMMDD')
    AND    START_TIMESTAMP < TO_DATE('20110309' ,'YYYYMMDD') + 1

  • Query throwing Exception as 'Query too large'

    HI,
    AM working on BI Content 7.
    I have created a query and the query name is TEST_RA_0064.
    when i am executing this query in the Analyser it is throwing the below mentioned errors.
    1. Query TEST_RA_0064 is too large.
    2. Program error in class SAPMSSY1 method:UNCAUGHT_EXCEPTION.
    Please help me.
    Thanks,
    Rajesh janardanan

    Execute this query via RSRT - for investigation purpose..
    Check for the detailed error message here.
    Hope it Helps
    Chetan
    @CP..

  • Error in SQL Query The text, ntext, and image data types cannot be compared or sorted, except when using IS NULL or LIKE operator. for the query

    hi Experts,
    while running SQL Query i am getting an error as
    The text, ntext, and image data types cannot be compared or sorted, except when using IS NULL or LIKE operator. for the query
    select  T1. Dscription,T1.docEntry,T1.Quantity,T1.Price ,
    T2.LineText
    from OQUT T0  INNER JOIN QUT1 T1 ON T0.DocEntry = T1.DocEntry INNER JOIN
    QUT10 T2 ON T1.DocEntry = T2.DocEntry where T1.DocEntry='590'
    group by  T1. Dscription,T1.docEntry,T1.Quantity,T1.Price
    ,T2.LineText
    how to resolve the issue

    Dear Meghanath,
    Please use the following query, Hope your purpose will serve.
    select  T1. Dscription,T1.docEntry,T1.Quantity,T1.Price ,
    CAST(T2.LineText as nvarchar (MAX))[LineText]
    from OQUT T0  INNER JOIN QUT1 T1 ON T0.DocEntry = T1.DocEntry LEFT OUTER JOIN
    QUT10 T2 ON T1.DocEntry = T2.DocEntry --where T1.DocEntry='590'
    group by  T1. Dscription,T1.docEntry,T1.Quantity,T1.Price
    ,CAST(T2.LineText as nvarchar (MAX))
    Regards,
    Amit

  • Using sql bulk copy throwing exception -The given value of type String from the data source cannot be converted to type int of the specified target column

    Hi All,
    I am reading notepads files and inserting data in sql tables from the notepad-
    while performing sql bulk copy on this line it throws exception - "bulkcopy.WriteToServer(dt); -"data type related(mentioned in subject )".
    Please go through my  logic and tell me what to change to avoid this error -
    public void Main()
    Dts.TaskResult = (int)ScriptResults.Success;
    string[] filePaths = Directory.GetFiles(@"C:\Users\jainruc\Desktop\Sudhanshu\master_db\Archive\test\content_insert\");
    for (int k = 0; k < filePaths.Length; k++)
    string[] lines = System.IO.File.ReadAllLines(filePaths[k]);
    //table name needs to extract after = sign
    string[] pathArr = filePaths[0].Split('\\');
    string tablename = pathArr[9].Split('.')[0];
    DataTable dt = new DataTable(tablename);
    |
    string[] arrColumns = lines[1].Split(new char[] { '|' });
    foreach (string col in arrColumns)
    dt.Columns.Add(col);
    for (int i = 2; i < lines.Length; i++)
    string[] columnsvals = lines[i].Split(new char[] { '|' });
    DataRow dr = dt.NewRow();
    for (int j = 0; j < columnsvals.Length; j++)
    //Console.Write(columnsvals[j]);
    if (string.IsNullOrEmpty(columnsvals[j]))
    dr[j] = DBNull.Value;
    else
    dr[j] = columnsvals[j];
    dt.Rows.Add(dr);
    SqlConnection conn = new SqlConnection();
    conn.ConnectionString = "Data Source=UI3DATS009X;" + "Initial Catalog=BHI_CSP_DB;" + "User Id=sa;" + "Password=3pp$erv1ce$4";
    conn.Open();
    SqlBulkCopy bulkcopy = new SqlBulkCopy(conn);
    bulkcopy.DestinationTableName = dt.TableName;
    bulkcopy.WriteToServer(dt);
    conn.Close();
    Issue 1:-
    I am reading notepad: getting all column and values in my data table now while inserting for date and time or integer field i need to do explicit conversion how to write for specific column before bulkcopy.WriteToServer(dt);
    Issue 2:- Notepad does not contains all columns nor in specific sequence in that case i can add few column ehich i am doing now but the issue is now data table will add my columns + notepad columns and while inserting how to assign in perticular colums?
    sudhanshu sharma Do good and cast it into river :)

    Hi,
    I think you'll have to do an explicit column mapping if they are not in exact sequence in both source and destination.
    Have a look at this link:
    https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopycolumnmapping(v=vs.110).aspx
    Good Luck!
    Kaur.
    Please mark as answer if this resolves your issue.

  • Regarding Exceptions of a SQL query

    Hi,
    We have a problem regarding the sql query shown below:
    select max(column1) into var1
    from table1
    where column2 = 100;
    We don't have any rows in the table1 but we are not getting the "NO data exception" while executing the query in a procedure.
    If we modify the query to
    select column1 into var1
    from table1
    where column2 = 100;
    then 'No data found' exception is raised.
    Can you please let us the reason behind this.
    Thanks in advance.
    Lakshmi

    Cut from Oracle documentation
    If a query with an aggregate function returns no rows or only rows with nulls for the argument to the aggregate function, the aggregate function returns null.
    AVG
    COUNT
    GROUPING
    MAX
    MIN
    STDDEV
    Aggregate function don't return 'No datafound Exception" I believe....Correcte me if i am Worng
    Ashok

  • How to retrieve a SQL query (in String format) from a PreparedStatement

    Hello all,
    I am in the process of unit testing an application accessing a Oracle 9i 9.2 RDBMS server with JDBC.
    My query is:
    As I have access to PreparedStatement and CallableStatement Java objets but not to the source queries which help create those objects?
    Is thtere a simple way by using an API, to retrieve the SQL command (with possible ? as placeholders for parameters).
    I have already looked at the API documentation for those two objets (and for the Statement and ResultSetmetaData objects too) but to no avail.
    Thank you for any help on this issue,
    Best regards,
    Benoît

    Sorry for having wasted your time... and for not understanding what you meant in your first reply.
    But the codlet was only to show the main idea:
    Here is the code which compiles OK for this approach to reach its intended goal:
    main class (file TestSuiteClass.java):
    import java.sql.*;
    import static java.lang.Class.*;
    * Created by IntelliJ IDEA.
    * User: bgilon
    * Date: 15/03/12
    * Time: 10:05
    * To change this template use File | Settings | File Templates.
    public class TestSuiteClass {
    public static void main(final String[] args) throws Exception {
    // Class.forName("oracle.jdbc.OracleDriver");
    final Connection mconn= new mConnection(
    DriverManager.getConnection("jdbc:oracle:thin:scott/tiger@host:port:service"));
    * final Statement lstmt= TestedClass.TestedMethod(mconn, ...);
    * final String SqlSrc= mconn.getSqlSrc(lstmt).toUpperCase(), SqlTypedReq= mconn.getTypReq(lstmt);
    * assertEquals("test 1", "UPDATE IZ_PD SET FIELD1= ? WHERE FIELDPK= ?", SqlSrc);
    Proxy class (file mConnector.java):
    import java.sql.*;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    import java.util.Properties;
    * Created by IntelliJ IDEA.
    * User: bgilon
    * Date: 15/03/12
    * Time: 10:05
    * To change this template use File | Settings | File Templates.
    * This file should be compiled with JDK 1.6, but can be used with previous JDK versions.
    * See OKwith1pN booleans usage for not throwing Exceptions as Unknown methods by the conn object...
    public final class mConnection implements Connection {
    private final Connection conn;
    private final List<Statement> Stmts= new ArrayList<Statement>();
    private final List<String> SqlSrcs= new ArrayList<String>();
    private final List<Integer> TypSrcs= new ArrayList<Integer>();
    private final static String jvmv= System.getProperty("java.specification.version");
    private static final boolean OKwith1p2;
    private static final boolean OKwith1p4; /* OKwith1p5, */
    private static final boolean OKwith1p6;
    static {
    /* jvmv= System.getProperty("java.version");
    System.out.println("jvmv = " + jvmv);
    jvmv= System.getProperty("java.vm.version");
    System.out.println("jvmv = " + jvmv); */
    System.out.println("jvmv = " + jvmv);
    OKwith1p2= (jvmv.compareTo("1.2") >= 0);
    OKwith1p4= (jvmv.compareTo("1.4") >= 0);
    // OKwith1p5= (jvmv.compareTo("1.5") >= 0);
    OKwith1p6= (jvmv.compareTo("1.6") >= 0);
    public String getSqlSrc(final Statement pstmt) {
    int ix= 0;
    for(Statement stmt : this.Stmts) {
    if(stmt == pstmt) return SqlSrcs.get(ix);
    ix+= 1;
    return null;
    static private final String[] TypeNames= new String[] { "Statement", "PreparedStatement", "CallableStatement" };
    public String getTypReq(final Statement pstmt) {
    int ix= 0;
    for(Statement stmt : this.Stmts) {
    if(stmt == pstmt) return TypeNames[TypSrcs.get(ix)];
    ix+= 1;
    return null;
    private void storedStatement(
    final Statement stmt,
    final String sqlSrc,
    final Integer typReq
    Stmts.add(stmt);
    SqlSrcs.add(sqlSrc);
    TypSrcs.add(typReq);
    public Connection getDecoratedConn() {
    return conn;
    mConnection(final Connection pconn) {
    this.conn= pconn;
    public boolean isClosed() throws SQLException {
    return conn.isClosed();
    public void rollback(Savepoint savepoint) throws SQLException {
    if(OKwith1p4) conn.rollback(savepoint);
    public boolean isReadOnly() throws SQLException {
    return conn.isReadOnly();
    public int getTransactionIsolation() throws SQLException {
    return conn.getTransactionIsolation();
    public void setTransactionIsolation(int level)throws SQLException {
    conn.setTransactionIsolation(level);
    public Properties getClientInfo() throws SQLException {
    return OKwith1p6 ? conn.getClientInfo() : null;
    public <T> T unwrap(Class<T> iface)
    throws SQLException {
    return conn.unwrap(iface);
    public void setAutoCommit(boolean auto) throws SQLException {
    conn.setAutoCommit(auto);
    public boolean getAutoCommit() throws SQLException {
    return conn.getAutoCommit();
    public Map<String,Class<?>> getTypeMap() throws SQLException {
    if(!OKwith1p2) return null;
    return conn.getTypeMap();
    public void setTypeMap(Map<String,Class<?>> map) throws SQLException {
    if(!OKwith1p2) return;
    conn.setTypeMap(map);
    public void setHoldability(final int holdability) throws SQLException {
    if(OKwith1p4) conn.setHoldability(holdability);
    public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
    return conn.createStruct(typeName, attributes);
    public void commit() throws SQLException {
    conn.commit();
    public void rollback() throws SQLException {
    conn.rollback();
    public boolean isValid(int timeout) throws SQLException {
    return OKwith1p6 && conn.isValid(timeout);
    public void clearWarnings() throws SQLException {
    conn.clearWarnings();
    public int getHoldability() throws SQLException {
    if(!OKwith1p4) return -1;
    return conn.getHoldability();
    public Statement createStatement() throws SQLException {
    return conn.createStatement();
    public PreparedStatement prepareStatement(final String SqlSrc) throws SQLException {
    if(!OKwith1p2) return null;
    final PreparedStatement lstmt= conn.prepareStatement(SqlSrc);
    storedStatement(lstmt, SqlSrc, 1);
    return lstmt;
    public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
    if(!OKwith1p4) return null;
    final PreparedStatement lstmt= conn.prepareStatement(sql, columnNames);
    storedStatement(lstmt, sql, 1);
    return lstmt;
    public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
    final PreparedStatement lstmt= conn.prepareStatement(sql, resultSetType, resultSetConcurrency);
    storedStatement(lstmt, sql, 1);
    return lstmt;
    public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
    final PreparedStatement lstmt= conn.prepareStatement(sql, columnIndexes);
    storedStatement(lstmt, sql, 1);
    return lstmt;
    public void setClientInfo(String name, String value) throws SQLClientInfoException {
    if(OKwith1p6)
    conn.setClientInfo(name, value);
    public PreparedStatement prepareStatement(final String SqlSrc,
    int resultType,
    int resultSetCurrency,
    int resultSetHoldability) throws SQLException {
    final PreparedStatement lstmt= conn.prepareStatement(SqlSrc, resultType, resultSetCurrency);
    storedStatement(lstmt, SqlSrc, 1);
    return lstmt;
    public PreparedStatement prepareStatement(final String SqlSrc,
    int autogeneratedkeys) throws SQLException {
    if(!OKwith1p4) return null;
    final PreparedStatement lstmt= conn.prepareStatement(SqlSrc, autogeneratedkeys);
    storedStatement(lstmt, SqlSrc, 1);
    return lstmt;
    public CallableStatement prepareCall(final String SqlSrc) throws SQLException {
    final CallableStatement lstmt= conn.prepareCall(SqlSrc);
    storedStatement(lstmt, SqlSrc, 2);
    return lstmt;
    public CallableStatement prepareCall(final String SqlSrc,
    int resultType,
    int resultSetCurrency,
    int resultSetHoldability) throws SQLException {
    if(!OKwith1p4) return null;
    final CallableStatement lstmt= conn.prepareCall(SqlSrc, resultType, resultSetCurrency, resultSetHoldability);
    storedStatement(lstmt, SqlSrc, 2);
    return lstmt;
    public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
    return OKwith1p6 ? conn.createArrayOf(typeName, elements) : null;
    public CallableStatement prepareCall(final String SqlSrc,
    int resultType,
    int resultSetCurrency) throws SQLException {
    if (!OKwith1p2) return null;
    final CallableStatement lstmt= conn.prepareCall(SqlSrc, resultType, resultSetCurrency);
    storedStatement(lstmt, SqlSrc, 2);
    return lstmt;
    public SQLXML createSQLXML() throws SQLException {
    return OKwith1p6 ? conn.createSQLXML() : null;
    public DatabaseMetaData getMetaData() throws SQLException {
    return conn.getMetaData();
    public String getCatalog() throws SQLException {
    return conn.getCatalog();
    public void setCatalog(final String str) throws SQLException {
    conn.setCatalog(str);
    public void setReadOnly(final boolean readonly) throws SQLException {
    conn.setReadOnly(readonly);
    public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
    return conn.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability);
    public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
    if(!OKwith1p2) return null;
    return conn.createStatement(resultSetType, resultSetConcurrency);
    public String nativeSQL(final String sql) throws SQLException {
    return conn.nativeSQL(sql);
    public void     releaseSavepoint(Savepoint savepoint) throws SQLException {
    if(OKwith1p4) conn.releaseSavepoint(savepoint);
    public Savepoint setSavepoint() throws SQLException {
    return OKwith1p4 ? conn.setSavepoint() : null;
    public Savepoint setSavepoint(final String str) throws SQLException {
    return OKwith1p4 ? conn.setSavepoint(str) : null;
    public boolean isWrapperFor(Class iface) throws SQLException {
    return conn.isWrapperFor(iface);
    public String getClientInfo(final String str) throws SQLException {
    return OKwith1p6 ? conn.getClientInfo(str) : null;
    public void setClientInfo(final Properties pro) throws SQLClientInfoException {
    if (OKwith1p6) conn.setClientInfo(pro);
    public Blob createBlob() throws SQLException {
    return OKwith1p6 ? conn.createBlob() : null;
    public Clob createClob() throws SQLException {
    return OKwith1p6 ? conn.createClob() : null;
    public NClob createNClob() throws SQLException {
    return OKwith1p6 ? conn.createNClob() : null;
    public SQLWarning getWarnings() throws SQLException {
    return conn.getWarnings();
    public void close() throws SQLException {
    conn.close();
    Final word:
    The final word about this is: there is currently three ways to obtain source SQL queries from compiled statement objects.
    a) Use a proxy class the mConnector above;
    b) Use a proxy JDBC driver as Log4JDBC;
    c) Use the trace facility of the driver (however, post analyzing the logs would depend upon the driver selected).
    Thank you for reading,
    Benoît

  • OutOfMemory error while executing sql query

    Hello!
    My program gets multiple datas from database in every ten minutes, and stores them in memory for hundreds of users, requesting datas via web-interface simoultaneously.
    I dont have access to change database structures, write stored procedures, etc, just read from db.
    There is a table in database with lot of million rows, and sometimes when I try to execute a SELECT on this table it takes minutes to get back the result.
    To avoid waiting for database server for a long time, I set querytimeout to 30 seconds.
    If the server throws back the execution with Query Timed out Exception, I want to 'forget' this data, and 0 value is acceptable because of fast run is more important. So I put the boolean broken variable to check if there is any problem with db server.
    The size of the used memory is about 150Mb if things going well, but I set the max heap to 512 MB, just in case anything happens.
    I'm logging all threads stacktrace, and free/used/allocated memory size in every 5 seconds.(threadwatching.log) 2.appendix
    Sometimes, not in every case (I dont know what is this depends on), when I get the next phase of refreshing cached datas (you can see it below), the process reaches the fiorst checkpoint (signed in code below), starts to execute the sql query, and never reaches the second checkpoint , but used memory growing 50-60 Mb-os in every 5 seconds, as I can see in threadwatching.log until it reaches the max memory and throws OutOfMemory error: java heap space.
    I'm using DbConnectionBroker for connection pooling, SQLCommandBean for handling Statements, PreparedStatements, etc, and jTDS jdbc connector.
    SQLCommandBean closes statements, resultsets, so these objects doesnt stays open.
    I cant figured out what causes the memory leak, if someone have an idea, please help me.
    1. Part of the cached data refreshing (DataFactory.createPCVPPMforSiemens()):
            PCVElement element = new PCVElement(m, ProcessControlView.PPM);
            String s = DateTime.getDate(interval.getStartDate());
            boolean broken=false;
            int value = 0;
            for (int j = 0; j < 48; j++) {
                try {
                    if (!broken) {
                        d1 = DateTime.getDate(new Date(start + ((j + 1) * 600000)));
                        sqlBean = new SQLCommandBean();
                        conn = broker.getConnection();
                        sqlBean.setConnection(conn);
                        sqlBean.setQueryTimeOut(30);
                        System.out.println(DateTime.getDate(new Date())+" "+m.getName()+"   "+j);// first checkpoint
                        value = SiemensWorks.getPCVPPM(sqlBean, statId, s, d1);
                        System.out.println(DateTime.getDate(new Date())+" "+m.getName()+"   "+j);// second checkpoint
                    } else value=0;
                } catch (Exception ex) {
                    System.out.println("ERROR: DataFactory.createPCVPPMforSiemens 1 :" + ex.getMessage());
                    ex.printStackTrace();
                    value = 0;
                    broken=true;
                } finally {
                    try {
                        broker.freeConnection(conn);
                    } catch (Exception ex) {}
                element.getAvgValues()[j] = value;
            }2. SiemensWorks.getPCVPPM()
        public static int getPCVPPM(SQLCommandBean sqlBean,int statID,String start,String end)
                throws SQLException, UnsupportedTypeException, NoSuchColumnException {
            sqlBean.setSqlValue(SiemensSQL.PCV_PPM);
            Vector values=new Vector();
            values.add(new StringValue(statID+""));
            values.add(new StringValue(start));
            values.add(new StringValue(end));
            sqlBean.setValues(values);
            Vector rows=sqlBean.executeQuery();
            if (rows==null || rows.size()==0) return 0;
            Row row=(Row)rows.firstElement();
            try {
                float ret=Float.parseFloat(row.getString(1));
                if (ret<=0) ret=0;
                return Math.round(ret);
            } catch (Exception ex) {
                return 0;
        }3. Part of Threadwatching.log
    2006-10-13 16:46:56 Name: SMT Refreshing Threads
    2006-10-13 16:46:56 Thread count: 4
    2006-10-13 16:46:56 Active count: 4
    2006-10-13 16:46:56 Active group count: 0
    2006-10-13 16:46:56 Daemon: false
    2006-10-13 16:46:56 Priority: 5
    2006-10-13 16:46:57 Free memory: 192,228,944 bytes
    2006-10-13 16:46:57 Max memory: 332,988,416 bytes
    2006-10-13 16:46:57 Memory in use: 140,759,472 bytes
    2006-10-13 16:46:57 ---------------------------------
    2006-10-13 16:46:57 0. Name: CachedLayerTimer
    2006-10-13 16:46:57 0. Id: 19
    2006-10-13 16:46:57 0. Priority: 5
    2006-10-13 16:46:57 0. Parent: SMT Refreshing Threads
    2006-10-13 16:46:57 0. State: RUNNABLE
    2006-10-13 16:46:57 0. Alive: true
    2006-10-13 16:46:57 java.io.FileOutputStream.close0(Native Method)
    2006-10-13 16:46:57 java.io.FileOutputStream.close(Unknown Source)
    2006-10-13 16:46:57 sun.nio.cs.StreamEncoder$CharsetSE.implClose(Unknown Source)
    2006-10-13 16:46:57 sun.nio.cs.StreamEncoder.close(Unknown Source)
    2006-10-13 16:46:57 java.io.OutputStreamWriter.close(Unknown Source)
    2006-10-13 16:46:57 xcompany.smtmonitor.chart.ChartCreator.createChart(ChartCreator.java:663)
    2006-10-13 16:46:57 xcompany.smtmonitor.chart.ChartCreator.create(ChartCreator.java:441)
    2006-10-13 16:46:57 xcompany.smtmonitor.CachedLayerRefreshenerTask.run(CachedLayerRefreshenerTask.java:463)
    2006-10-13 16:46:57 java.util.TimerThread.mainLoop(Unknown Source)
    2006-10-13 16:46:57 java.util.TimerThread.run(Unknown Source)
    Software runs well until I get the DataFactory.createPCVPPMforSiemens function in my code ->
    2006-10-13 16:47:01 Name: SMT Refreshing Threads
    2006-10-13 16:47:01 Thread count: 4
    2006-10-13 16:47:01 Active count: 4
    2006-10-13 16:47:01 Active group count: 0
    2006-10-13 16:47:01 Daemon: false
    2006-10-13 16:47:01 Priority: 5
    2006-10-13 16:47:02 Free memory: 189,253,304 bytes
    2006-10-13 16:47:02 Max memory: 332,988,416 bytes
    2006-10-13 16:47:02 Memory in use: 143,735,112 bytes
    2006-10-13 16:47:02 ---------------------------------
    2006-10-13 16:47:02 0. Name: CachedLayerTimer
    2006-10-13 16:47:02 0. Id: 19
    2006-10-13 16:47:02 0. Priority: 5
    2006-10-13 16:47:02 0. Parent: SMT Refreshing Threads
    2006-10-13 16:47:02 0. State: RUNNABLE
    2006-10-13 16:47:02 0. Alive: true
    2006-10-13 16:47:02 java.util.LinkedList$ListItr.previous(Unknown Source)
    2006-10-13 16:47:02 net.sourceforge.jtds.util.TimerThread.setTimer(TimerThread.java:174)
    2006-10-13 16:47:02 net.sourceforge.jtds.jdbc.TdsCore.wait(TdsCore.java:3734)
    2006-10-13 16:47:02 net.sourceforge.jtds.jdbc.TdsCore.executeSQL(TdsCore.java:997)
    2006-10-13 16:47:02 net.sourceforge.jtds.jdbc.JtdsStatement.executeSQLQuery(JtdsStatement.java:320)
    2006-10-13 16:47:02 net.sourceforge.jtds.jdbc.JtdsPreparedStatement.executeQuery(JtdsPreparedStatement.java:667)
    2006-10-13 16:47:02 xcompany.database.sql.SQLCommandBean.executeQuery(SQLCommandBean.java:91)
    2006-10-13 16:47:02 xcompany.smtmonitor.data.SiemensWorks.getPCVPPM(SiemensWorks.java:409)
    2006-10-13 16:47:02 xcompany.smtmonitor.data.DataFactory.createPCVPPMforSiemens(DataFactory.java:6103)
    2006-10-13 16:47:02 xcompany.smtmonitor.data.DataFactory.refreshProcessControlView(DataFactory.java:5791)
    2006-10-13 16:47:02 xcompany.smtmonitor.CachedLayerRefreshenerTask.run(CachedLayerRefreshenerTask.java:514)
    2006-10-13 16:47:02 java.util.TimerThread.mainLoop(Unknown Source)
    2006-10-13 16:47:02 java.util.TimerThread.run(Unknown Source)
    2006-10-13 16:47:06 Name: SMT Refreshing Threads
    2006-10-13 16:47:06 Thread count: 4
    2006-10-13 16:47:06 Active count: 4
    2006-10-13 16:47:06 Active group count: 0
    2006-10-13 16:47:06 Daemon: false
    2006-10-13 16:47:06 Priority: 5
    2006-10-13 16:47:08 Free memory: 127,428,192 bytes
    2006-10-13 16:47:08 Max memory: 332,988,416 bytes
    2006-10-13 16:47:08 Memory in use: 205,560,224 bytes
    2006-10-13 16:47:08 ---------------------------------
    2006-10-13 16:47:08 0. Name: CachedLayerTimer
    2006-10-13 16:47:08 0. Id: 19
    2006-10-13 16:47:08 0. Priority: 5
    2006-10-13 16:47:08 0. Parent: SMT Refreshing Threads
    2006-10-13 16:47:08 0. State: RUNNABLE
    2006-10-13 16:47:08 0. Alive: true
    2006-10-13 16:47:08 java.util.LinkedList$ListItr.previous(Unknown Source)
    2006-10-13 16:47:08 net.sourceforge.jtds.util.TimerThread.setTimer(TimerThread.java:174)
    2006-10-13 16:47:08 net.sourceforge.jtds.jdbc.TdsCore.wait(TdsCore.java:3734)
    2006-10-13 16:47:08 net.sourceforge.jtds.jdbc.TdsCore.executeSQL(TdsCore.java:997)
    2006-10-13 16:47:08 net.sourceforge.jtds.jdbc.JtdsStatement.executeSQLQuery(JtdsStatement.java:320)
    2006-10-13 16:47:08 net.sourceforge.jtds.jdbc.JtdsPreparedStatement.executeQuery(JtdsPreparedStatement.java:667)
    2006-10-13 16:47:08 xcompany.database.sql.SQLCommandBean.executeQuery(SQLCommandBean.java:91)
    2006-10-13 16:47:08 xcompany.smtmonitor.data.SiemensWorks.getPCVPPM(SiemensWorks.java:409)
    2006-10-13 16:47:08 xcompany.smtmonitor.data.DataFactory.createPCVPPMforSiemens(DataFactory.java:6103)
    2006-10-13 16:47:08 xcompany.smtmonitor.data.DataFactory.refreshProcessControlView(DataFactory.java:5791)
    2006-10-13 16:47:08 xcompany.smtmonitor.CachedLayerRefreshenerTask.run(CachedLayerRefreshenerTask.java:514)
    2006-10-13 16:47:08 java.util.TimerThread.mainLoop(Unknown Source)
    2006-10-13 16:47:08 java.util.TimerThread.run(Unknown Source)
    2006-10-13 16:47:12 Name: SMT Refreshing Threads
    2006-10-13 16:47:12 Thread count: 4
    2006-10-13 16:47:12 Active count: 4
    2006-10-13 16:47:12 Active group count: 0
    2006-10-13 16:47:12 Daemon: false
    2006-10-13 16:47:12 Priority: 5
    2006-10-13 16:47:15 Free memory: 66,760,208 bytes
    2006-10-13 16:47:15 Max memory: 332,988,416 bytes
    2006-10-13 16:47:15 Memory in use: 266,228,208 bytes
    2006-10-13 16:47:15 ---------------------------------
    2006-10-13 16:47:15 0. Name: CachedLayerTimer
    2006-10-13 16:47:15 0. Id: 19
    2006-10-13 16:47:15 0. Priority: 5
    2006-10-13 16:47:15 0. Parent: SMT Refreshing Threads
    2006-10-13 16:47:15 0. State: RUNNABLE
    2006-10-13 16:47:15 0. Alive: true
    2006-10-13 16:47:15 java.util.LinkedList.addBefore(Unknown Source)
    2006-10-13 16:47:15 java.util.LinkedList.access$300(Unknown Source)
    2006-10-13 16:47:15 java.util.LinkedList$ListItr.add(Unknown Source)
    2006-10-13 16:47:15 net.sourceforge.jtds.util.TimerThread.setTimer(TimerThread.java:175)
    2006-10-13 16:47:15 net.sourceforge.jtds.jdbc.TdsCore.wait(TdsCore.java:3734)
    2006-10-13 16:47:15 net.sourceforge.jtds.jdbc.TdsCore.executeSQL(TdsCore.java:997)
    2006-10-13 16:47:15 net.sourceforge.jtds.jdbc.JtdsStatement.executeSQLQuery(JtdsStatement.java:320)
    2006-10-13 16:47:15 net.sourceforge.jtds.jdbc.JtdsPreparedStatement.executeQuery(JtdsPreparedStatement.java:667)
    2006-10-13 16:47:15 xcompany.database.sql.SQLCommandBean.executeQuery(SQLCommandBean.java:91)
    2006-10-13 16:47:15 xcompany.smtmonitor.data.SiemensWorks.getPCVPPM(SiemensWorks.java:409)
    2006-10-13 16:47:15 xcompany.smtmonitor.data.DataFactory.createPCVPPMforSiemens(DataFactory.java:6103)
    2006-10-13 16:47:15 xcompany.smtmonitor.data.DataFactory.refreshProcessControlView(DataFactory.java:5791)
    2006-10-13 16:47:15 xcompany.smtmonitor.CachedLayerRefreshenerTask.run(CachedLayerRefreshenerTask.java:514)
    2006-10-13 16:47:15 java.util.TimerThread.mainLoop(Unknown Source)
    2006-10-13 16:47:15 java.util.TimerThread.run(Unknown Source)
    2006-10-13 16:47:17 Name: SMT Refreshing Threads
    2006-10-13 16:47:17 Thread count: 4
    2006-10-13 16:47:17 Active count: 4
    2006-10-13 16:47:17 Active group count: 0
    2006-10-13 16:47:17 Daemon: false
    2006-10-13 16:47:17 Priority: 5
    2006-10-13 16:47:20 Free memory: 23,232,496 bytes
    2006-10-13 16:47:20 Max memory: 332,988,416 bytes
    2006-10-13 16:47:20 Memory in use: 309,755,920 bytes
    2006-10-13 16:47:20 ---------------------------------
    2006-10-13 16:47:20 0. Name: CachedLayerTimer
    2006-10-13 16:47:20 0. Id: 19
    2006-10-13 16:47:20 0. Priority: 5
    2006-10-13 16:47:20 0. Parent: SMT Refreshing Threads
    2006-10-13 16:47:20 0. State: RUNNABLE
    2006-10-13 16:47:20 0. Alive: true
    2006-10-13 16:47:20 net.sourceforge.jtds.util.TimerThread.setTimer(TimerThread.java:171)
    2006-10-13 16:47:20 net.sourceforge.jtds.jdbc.TdsCore.wait(TdsCore.java:3734)
    2006-10-13 16:47:20 net.sourceforge.jtds.jdbc.TdsCore.executeSQL(TdsCore.java:997)
    2006-10-13 16:47:20 net.sourceforge.jtds.jdbc.JtdsStatement.executeSQLQuery(JtdsStatement.java:320)
    2006-10-13 16:47:20 net.sourceforge.jtds.jdbc.JtdsPreparedStatement.executeQuery(JtdsPreparedStatement.java:667)
    2006-10-13 16:47:20 xcompany.database.sql.SQLCommandBean.executeQuery(SQLCommandBean.java:91)
    2006-10-13 16:47:20 xcompany.smtmonitor.data.SiemensWorks.getPCVPPM(SiemensWorks.java:409)
    2006-10-13 16:47:20 xcompany.smtmonitor.data.DataFactory.createPCVPPMforSiemens(DataFactory.java:6103)
    2006-10-13 16:47:20 xcompany.smtmonitor.data.DataFactory.refreshProcessControlView(DataFactory.java:5791)
    2006-10-13 16:47:20 xcompany.smtmonitor.CachedLayerRefreshenerTask.run(CachedLayerRefreshenerTask.java:514)
    2006-10-13 16:47:20 java.util.TimerThread.mainLoop(Unknown Source)
    2006-10-13 16:47:20 java.util.TimerThread.run(Unknown Source)
    2006-10-13 16:47:23 Name: SMT Refreshing Threads
    2006-10-13 16:47:23 Thread count: 4
    2006-10-13 16:47:23 Active count: 4
    2006-10-13 16:47:23 Active group count: 0
    2006-10-13 16:47:23 Daemon: false
    2006-10-13 16:47:23 Priority: 5
    2006-10-13 16:47:26 Free memory: 4,907,336 bytes
    2006-10-13 16:47:26 Max memory: 332,988,416 bytes
    2006-10-13 16:47:26 Memory in use: 328,083,768 bytes
    2006-10-13 16:47:26 ---------------------------------
    2006-10-13 16:47:26 0. Name: CachedLayerTimer
    2006-10-13 16:47:26 0. Id: 19
    2006-10-13 16:47:26 0. Priority: 5
    2006-10-13 16:47:26 0. Parent: SMT Refreshing Threads
    2006-10-13 16:47:26 0. State: RUNNABLE
    2006-10-13 16:47:26 0. Alive: true
    2006-10-13 16:47:26 java.util.LinkedList.addBefore(Unknown Source)
    2006-10-13 16:47:26 java.util.LinkedList.access$300(Unknown Source)
    2006-10-13 16:47:26 java.util.LinkedList$ListItr.add(Unknown Source)
    2006-10-13 16:47:26 net.sourceforge.jtds.util.TimerThread.setTimer(TimerThread.java:175)
    2006-10-13 16:47:26 net.sourceforge.jtds.jdbc.TdsCore.wait(TdsCore.java:3734)
    2006-10-13 16:47:26 net.sourceforge.jtds.jdbc.TdsCore.executeSQL(TdsCore.java:997)
    2006-10-13 16:47:26 net.sourceforge.jtds.jdbc.JtdsStatement.executeSQLQuery(JtdsStatement.java:320)
    2006-10-13 16:47:26 net.sourceforge.jtds.jdbc.JtdsPreparedStatement.executeQuery(JtdsPreparedStatement.java:667)
    2006-10-13 16:47:26 xcompany.database.sql.SQLCommandBean.executeQuery(SQLCommandBean.java:91)
    2006-10-13 16:47:26 xcompany.smtmonitor.data.SiemensWorks.getPCVPPM(SiemensWorks.java:409)
    2006-10-13 16:47:26 xcompany.smtmonitor.data.DataFactory.createPCVPPMforSiemens(DataFactory.java:6103)
    2006-10-13 16:47:26 xcompany.smtmonitor.data.DataFactory.refreshProcessControlView(DataFactory.java:5791)
    2006-10-13 16:47:26 xcompany.smtmonitor.CachedLayerRefreshenerTask.run(CachedLayerRefreshenerTask.java:514)
    2006-10-13 16:47:26 java.util.TimerThread.mainLoop(Unknown Source)
    2006-10-13 16:47:26 java.util.TimerThread.run(Unknown Source)
    2006-10-13 16:47:35 Name: SMT Refreshing Threads
    2006-10-13 16:47:37 Thread count: 4
    2006-10-13 16:47:38 Active count: 4
    2006-10-13 16:47:38 Active group count: 0
    2006-10-13 16:47:38 Daemon: false
    2006-10-13 16:47:38 Priority: 5
    2006-10-13 16:47:42 Free memory: 35,316,120 bytes
    2006-10-13 16:47:42 Max memory: 332,988,416 bytes
    2006-10-13 16:47:42 Memory in use: 297,672,296 bytes
    2006-10-13 16:47:42 ---------------------------------
    2006-10-13 16:47:42 0. Name: CachedLayerTimer
    2006-10-13 16:47:42 0. Id: 19
    2006-10-13 16:47:42 0. Priority: 5
    2006-10-13 16:47:42 0. Parent: SMT Refreshing Threads
    2006-10-13 16:47:42 0. State: TIMED_WAITING
    2006-10-13 16:47:42 0. Alive: true
    2006-10-13 16:47:42 java.lang.Object.wait(Native Method)
    2006-10-13 16:47:42 java.util.TimerThread.mainLoop(Unknown Source)
    2006-10-13 16:47:42 java.util.TimerThread.run(Unknown Source)
    4. Tomcat default logging file:
    2006-10-13 16:47:36 ERROR CachedLayerRefreshenerTask: external error: Java heap space
    5. DbConnectionBroker (connection pooling) logging file:
    Handing out connection 1 --> 10/13/2006 04:47:01 PM
    Handing out connection 0 --> 10/13/2006 04:47:01 PM
    Handing out connection 1 --> 10/13/2006 04:47:01 PM
    Handing out connection 0 --> 10/13/2006 04:47:02 PM
    Warning. Connection 0 in use for 3141 ms
    Warning. Connection 0 in use for 24891 ms
    ----> Error: Could not free connection!!!
    I would appreciate for any help.

    What does your query bring back from this table?This is the query:
    SELECT case sum(c.picked) when 0 then 0 else
    ((sum(c.picked)-(sum(c.picked)-(sum(c.vacuum)+sum(c.id
    ent))))*cast((1000000/cast(sum(c.picked) as float))
    as bigint)) end as PPM
    FROM sip_comp c
    LEFT JOIN sip_pcb pc ON pc.id=c.pcbid
    LEFT JOIN sip_period p on p.id=pc.periodid
    WHERE p.stationid=? AND pc.time BETWEEN ? AND ?Has anybody who knows SQL tried EXPLAIN PLAN to optimize this table? You're joining on a table with a million rows and you're wondering why the performance is poor?
    What is the index situation with these tables?
    .> When I execute it from query manager, it takes from 1
    to 60 secs depend on servers availability. So how will that be any different for JDBC and Java?
    ..> You're right. Thats why I am here.
    What I mean by that is we can't read minds, either. You need to get some hard data to tell you where the bottleneck is. Asking at a forum won't help.
    But tell me, if the java process enters to this query
    execution, and doesnt quit until OOM thrown, how can
    be the problem in caching?I was guessing about caching, because I didn't know what the query was.
    You expect a lot.
    .> No.
    Then how do you ever expect to solve this?
    I tried YourKit Profiler at home, where I'm
    developing software, but this OOM never thrown here,
    even if I have the same database size.Then you aren't replicating the problem. You have to run it on the system that has the problem if you're going to solve it.
    YourKit isn't an industry leader. How well do you know how to use it?
    It just happened at the company where the system
    runs, and I cannot run this profiler there because
    the PC where my tomcat runs dramatically slowed.You have to run something to figure out what the problem is. What about Log4J, some trace logging statements and a batch job to harvest the log?
    Bottom line: you've got to be a scientist and get some real data. We can theorize all we want here, but that won't get you to a solution.
    %

  • Oaf: putting validation in VO based on sql query

    Hi All,
    I need few inputs for the customization of OAF page.
    Business Need: Restriction of special character in supplier oaf pages for supplier name.
    There are 3 oaf pages involved in supplier creation/update for R 12.1.3
    1)     oracle\apps\pos\supplier\webui\OrganizationPG (underlying VO is sql query based).
    2)     oracle\apps\pos\supplier\webui\QuickUpdatePG (underlying VO is sql query based).
    3)     oracle\apps\pos\supplier\webui\SuppCrtPG (underlying VO is based on EO - HzPuiOrgProfileQuickEOEx) .
    For pages referring EO, we have extended the underlying EO and override the validateEntity() method to throw the OAAttrValException. After substitution, validation is working.
    For VO based on query, the standard AM’s are instantiating the VO and using Rowimpl class they are setting the attributes.
    Question: How to enforce validation logic in VO or AM in such cases where oracle standard code is instantiating the VO dynamically?
    One possible solution is to use the PPR event on input text message bean and catch it in custom controller’s processFormRequest method and before super. processFormRequest(), we can put the validation.
    Is there any other way to achieve it?

    VO extension will not work as the
    Standard Controller code : oracle.apps.pos.supplier.webui.QuickUpdateCO is calling the AM's method on the click of save button and AM is dynamically invoking the methods in VO.
    Standard Controller code:
    OAApplicationModule oaapplicationmodule = oapagecontext.getApplicationModule(oawebbean);
    if(oapagecontext.getParameter("btnSave") != null)
    oaapplicationmodule.invokeMethod("updateVendor");
    oaapplicationmodule.invokeMethod("updateVendorSites");
    oaapplicationmodule.getTransaction().commit();
    Corressponding standard standard AM code...
    CallableStatement callablestatement;
    Exception exception;
    oadbtransaction = getOADBTransaction();
    connection = oadbtransaction.getJdbcConnection();
    Object obj = null;
    oaviewobjectimpl = (OAViewObjectImpl)findViewObject("SupplierVO");
    callablestatement = null;
    try
    callablestatement = oadbtransaction.createCallableStatement(" BEGIN savepoint upd_vndr_ab ; END;", 0);
    callablestatement.executeQuery();
    catch(SQLException sqlexception1)
    throw OAException.wrapperException(sqlexception1);
    finally
    if(callablestatement == null) goto L0; else goto L0
    if(callablestatement != null)
    try
    callablestatement.close();
    catch(SQLException sqlexception) { }
    break MISSING_BLOCK_LABEL_97;
    try
    callablestatement.close();
    catch(SQLException sqlexception2) { }
    throw exception;
    VendorsVORowImpl vendorsvorowimpl;
    label0:
    oaviewobjectimpl.reset();
    vendorsvorowimpl = (VendorsVORowImpl)oaviewobjectimpl.first();
    String s = vendorsvorowimpl.getPosModified();
    String s1 = vendorsvorowimpl.getHzModified();
    Number number = vendorsvorowimpl.getVendorId();
    int i = number.intValue();.....
    Extending the VO will not server the good as the handle will not be given to extended class....
    Edited by: user13791631 on Jun 20, 2012 9:29 PM

  • Need Help in SQL Query

    Hi all,
    I have data in the following manner:
    CASE_NUMBER HOURS FLAG
    1000 10 0
    1000 20 0
    1000 30 1
    1000 40 0
    1000 50 1
    Here I need to Calculate the total hours for a Case_number till i see the flag as 1.
    Here the result must be 10+20+30 Hrs
    Another Example
    CASE_NUMBER HOURS FLAG
    2000 10 1
    2000 20 1
    Here the result must be only 10.
    I am struggling to write a SQL query for this.
    Anyones help will be very much greatful
    Thanks in Advance
    Regards,
    Sengathir Subbarayan

    Look up analytical functions.
    something like sum(hours) OVER (PARTITION BY case_number ORDER BY something)
    will give you the sum for all rows.
    Then you probably want to "throw away" those rows after the flag maybe by summing the flag column too, and throw away all those where the flag is greater than 1 and where it is equal to 1 except for the first one.
    I suspect you actually have some other column (other than the number of hours) that define your order - that's what you put in the ORDER BY.
    Jon

  • Creating a dynamic SQL query builder class

    I have a jobs table where each row contains information about jobs run on a machine. I have a web view of this database which shows different information and queries for this information are built using the following fields:
    TYPE
    TITLE
    NODE
    STATUS (an array of 4 different possible statuses)
    TIMESTAMP
    GUID (will be used when a view of a specific job (row in the table) is requested, no other search criteria needed when this view is required.)
    All the criteria will be passed from the view layer into a search criteria object which is then passed to the DAO class which passes it to a BuildSQL class to use it to build the SQL.
    There are many different "views" of the data which will result in many different combinations of criteria being passed down to the data access layer. (for example a status of failed and a timestamp resulting in all the jobs run in the last 2 hours)
    As there are a number of different search criteria used in each query I'm having trouble designing the class to dynamically build the query. Are there any standard ways of doing this out there that could guide me?
    At the moment I'm seeing this class as being a large combination of if statements and not really being very dynamic.
    I was thinking maybe checking all the criteria to see if its null, if so ignore it straight away and then running through all the other criteria and appending one by one to the may SELECT which has already been created. Quite how i'd decided whether it would need an AND or OR before it I dont know.
    Are there any standard proven ways to approach this because i've done a search here and on google and not really come back with much, so any advice would be great. I've got to say I'm pretty new to java and don't really have many bright ideas here!

    Well my dear friend... I did something special for a business logic support to an web autocomplete component.
    The criteria building was based on a custom variable into the SQL statement:
    SELECT * FROM TABLE WHERE __MC__ AND (FIXED CRITERIA)
    Where:
    *FIXED CRITERIA: Is a fixed criteria that doesn't variate
    *__MC__: Is a "custom variable" defined for me to make the replacement.
    There are two main clases:
    *SQLBuilder: It has many logic to build SQL Statements
    *Multicriteria: It has the specific logic to insert into a SQL statement multiple criterias
    // The SQLBuilder class
    public class SQLBuilder {
        public static final String MC = "__MC__";
        static String buildMultiCriteria(String sql, Object[] params) throws Exception {
            for(int i=0; i<params.length; i++) {
                if(params[i] instanceof MultiCriteria) {
                    sql = sql.replaceFirst("__MC__",
                            ((MultiCriteria)params).getCriteria());
    params[i] = null;
    return sql;
    // The MultiCriteria class
    public class MultiCriteria {
    public static final int BEGINS = 0;
    public static final int ENDS = 1;
    public static final int CONTAINS = 2;
    private String criteria = null;
    public MultiCriteria(String[] fields, String value, int type) throws Exception {
    String[] tokens = value.split(" ");
    StringBuffer sb = new StringBuffer("(");
    for(int i=0; i<fields.length; i++) {
    for(int j=0; j<tokens.length; j++) {
    if(tokens[j].length()>0) {
         sb.append(fields[i].toUpperCase());
         sb.append(" LIKE '");
         sb.append(toType(tokens[j], type));
         sb.append("'");
         if(j<tokens.length-1) sb.append(" OR ");
    if(i<fields.length-1) sb.append(" OR ");
    sb.append(")");
    criteria = sb.toString();
    public String getCriteria() {
    return criteria;
    private final String toType(String value, int type) throws Exception {
    switch(type) {
         case BEGINS:
         value = value + "%";
         break;
         case ENDS:
         value = "%" + value;      
         break;
         case CONTAINS:
         value = "%" + value + "%";      
         break;
         default:
         throw new Exception("Undefined MutiCriteria type");
    return value;
    // I use the MultiCriteria this way
    // criteria is a string introduced in a html input text
    // The class splits the string by " " and ensemble multiple criterias
    // for the given fields permuting them with the tokens resulting of the
    // split
    MultiCriteria mc = new MultiCriteria(
    new String[] {"FIELD_01", "FIELD_02"},
         criteria,
         MultiCriteria.CONTAINS
    I think this idea could help you.
    Anything else, write me at [email protected]
    Best Regards,

  • Java.sql.SQLException: Io exception: End of TNS data channel

    Hello folks,
    Has amyone encountered this exception? If so, could you please shed some light for what might be going wrong?
    Here is my confuguration:
    400MB RAM
    1.2GHTz processor
    Win2K Pro
    Oracle server 9.0.1
    JDBC Thin driver (libs for 9.0.1)
    Scenario:
    My Java code uses Oracle Spatial to insert SDO_GEOMETRY objects into my DB model.
    I have a config file where I store my connection properties, e.g.,
    <DBConnection name="twatest">
    <JDBCDriver>oracle.jdbc.driver.OracleDriver</JDBCDriver>
    <URL>jdbc:oracle:thin:@saturn:1521:saturn</URL>
    <Username>user1</Username>
    <Password>twatest</Password>
    </DBConnection>
    We have 2 schemas defined: user1 and twatest.
    The problem first occured when I switched from user1 to twatest. Consequent attempt to run the process as user user1 failed! The Java SQL statements do not use schemas (so they default, I suppose, to the default schema for that particular user, in our case being user1-->user1, twatest-->twatest).
    The problem happens in the following Java class (search for "HERE" to see where exactly the problem occurs):
    package com.vividsolutions.twatest;
    import java.util.*;
    import java.sql.*;
    import oracle.sql.*;
    import oracle.sdoapi.OraSpatialManager;
    import oracle.sdoapi.geom.*;
    import oracle.sdoapi.adapter.*;
    import oracle.sdoapi.sref.*;
    import com.vividsolutions.twatest.parser.*;
    import com.vividsolutions.twatest.config.*;
    import com.vividsolutions.twatest.model.*;
    * This class is responsible for loading lakes into the SDO Oracle Spatial DB.
    public class LakeLoader
    static boolean initialized = false;
    private static GeometryFactory gF;
    private static SRManager srManager;
    private static SpatialReference sref;
    private static GeometryAdapter sdoAdapter;
    public static void loadLake(EdgedLake slake, Connection conn) throws Exception {
    com.vividsolutions.jts.geom.Envelope e = slake.getEnvelope();
    if (e == null) {
    System.out.println("Invalid envilope (feature ID="+slake.getFeatureId()+")! Ignoring...");
    return; // ignore lake - it's invalid (no envilope)
    if (!initialized) {
    initialize(conn);
    initialized = true;
    Geometry geom;
    STRUCT str;
    // insert Lake
    String lakeQuery = "INSERT INTO lake " +
    "(lake_id, area, bounding_box, name, instantiation_date) " +
    "VALUES(?,?,?,?,?)";
    PreparedStatement ps = conn.prepareStatement(lakeQuery);
    int lakeId = getId(Lake.ID, conn);
    ps.setInt(1, lakeId);
    ps.setDouble(2, Double.parseDouble(slake.getArea()));
    // Creates a 2-D rectangle (special case of Polygon geometry).
    geom = gF.createRectangle(e.getMinX(), e.getMinY(), e.getMaxX(), e.getMaxY());
    ps.setObject(3, sdoAdapter.exportGeometry(STRUCT.class, geom));
    ps.setString(4, slake.getName());
    ps.setTimestamp(5, new Timestamp(new java.util.Date().getTime()));
    ps.executeUpdate(); // <-- HERE I got: java.sql.SQLException: Io exception: End of TNS data channel
    //ps.close();
    String ringQuery = null;
    int ringId = 0;
    List shellEdges = slake.getShellEdges();
    if (shellEdges != null && shellEdges.size() > 0) { // if there is valid shell, insert it...
    // insert shell Rings
    ringQuery = "INSERT INTO ring (ring_id, lake_id, type) VALUES(?,?,?)";
    ps = conn.prepareStatement(ringQuery);
    ringId = getId(Ring.ID, conn);
    ps.setInt(1, ringId);
    ps.setInt(2, lakeId);
    ps.setString(3, Ring.SHELL);
    ps.executeUpdate();
    //ps.close();
    // insert shell ring Edges
    insertEdges(shellEdges, lakeId, Ring.SHELL, ringId, conn);
    List holeEdges = slake.getHoleEdges();
    if (holeEdges != null && holeEdges.size() > 0) { // if there are valid holes, insert them...
    // insert hole Rings
    ringQuery = "INSERT INTO ring (ring_id, lake_id, type) VALUES(?,?,?)";
    ps = conn.prepareStatement(ringQuery);
    ringId = getId(Ring.ID, conn);
    ps.setInt(1, ringId);
    ps.setInt(2, lakeId);
    ps.setString(3, Ring.HOLE);
    ps.executeUpdate();
    //ps.close();
    // insert hole ring Edges
    insertEdges(holeEdges, lakeId, Ring.HOLE, ringId, conn);
    ps.close();
    private static void insertEdges(List edges, int lakeId, String ringType,
    int ringId, Connection conn) throws Exception {
    if (!initialized) {
    initialize(conn);
    initialized = true;
    Geometry geom;
    STRUCT str;
    // insert shell ring Edges
    String edgeQuery = "INSERT INTO edge " +
    "(edge_id, lake_id, ring_type, ring_id, edge_sequence, shape) " +
    "VALUES(?,?,?,?,?,?)";
    int edge_sequence = 0;
    for (Iterator it=edges.iterator(); it.hasNext(); ) {
    Edge edge = (Edge)it.next();
    geom = gF.createLineString(LakeFactory.edgeToArray2D(edge)); // 2-dimensional coordinates
    PreparedStatement ps = conn.prepareStatement(edgeQuery);
    int edgeId = getId(Edge.ID, conn);
    ps.setInt(1, edgeId);
    ps.setInt(2, lakeId);
    ps.setString(3, ringType);
    ps.setInt(4, ringId);
    ps.setInt(5, edge_sequence++);
    ps.setObject(6, sdoAdapter.exportGeometry(STRUCT.class, geom));
    ps.executeUpdate();
    ps.close();
    * @param key This can be: "lake", "ring", or "edge".
    * @param conn The connection to use.
    * @return the unique ID corresponding to the given key.
    public static int getId(String key, Connection conn) {
    int id = -1;
    try {
    String query = "SELECT "+key+"_SEQUENCE.NEXTVAL FROM DUAL";
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery(query);
    while (rs.next()) {
    id = rs.getInt(1);
    stmt.close();
    } catch(SQLException sqle) {
    sqle.printStackTrace();
    return id;
    private static void initialize(Connection conn) throws Exception {
    gF = OraSpatialManager.getGeometryFactory();
    // Set spatial reference system in which the geometries will be created
    srManager = OraSpatialManager.getSpatialReferenceManager(conn);
    sref = srManager.retrieve(8307);
    gF.setSpatialReference(sref);
    sdoAdapter = OraSpatialManager.getGeometryAdapter("SDO", "8.1.6",
    null, STRUCT.class, null, conn);
    public static void main(String args[]) throws Exception
    String[] xmlLakeFiles = {
    "lakes101to1400.xml",
    "lakes1401to10000.xml",
    "lakes10001to20000.xml",
    "lakes20001to30000.xml",
    "lakes30001to40000.xml",
    "lakes40001to50000.xml",
    "lakes50001to60000.xml"
    PropertyManager pm = new PropertyManager();
    int numberOfLoadedLakes = 0;
    try {
    pm.initialize();
    Map modelMap = (Map)pm.get(XMLConfigFile.MODEL_MAP);
    LakeModel lakeModel = (LakeModel)modelMap.get(LREConcreteLakeModel.NAME);
    Connection connection = ConnectionManager.getConnection();
    lakeModel.setConnection(connection);
    for (int i=0; i<xmlLakeFiles.length; i++) {
    long then = System.currentTimeMillis();
    System.out.println("Loading lake "+xmlLakeFiles[i]+"...");
    numberOfLoadedLakes = lakeModel.loadModel(xmlLakeFiles);
    long now = System.currentTimeMillis();
    System.out.println("Loaded "+numberOfLoadedLakes+" lakes!");
    System.out.println("Execution time: "+(now-then)/1000+" seconds!");
    System.out.println("Loading lake "+xmlLakeFiles[i]+"...done!");
    connection.close();
    } catch(Exception e) {
    e.printStackTrace();
    My client class calls LakeLoader.loadLake() method in a loop to load a bunch of Lake objects into the DB. The first lake in the list is created without problems, but when the 2-nd lake is being inserted, I get an exception at the preparedStatement.executeUpdate() statement. This happens consistently.
    I tried to find information on this on the net, but seems that this problem only happened when people dealt with LOBs?!
    Thank you very much!
    Georgi

    Suresh -- I'd probably log a TAR with Oracle support for this question if you definitely need it resolved. Support have access to all manner of existing cases, so this may be something they have seen before.
    cheers
    -steve-

  • Row_number() -SQL function throws error - SAP B1 2005 B - PL 36

    hi experts,
    when i try 2 run "SELECT * FROM (SELECT ROW_NUMBER() OVER (ORDER BY CardName) AS RowNo,CardCode,CardName FROM OCRD Where CARDTYPE='C') AS OCRD"
    query in SAP B1 2005 B, PL-36 it shows an error -server throw an exception.
    anybody can comment on it
    thanks in advance
    jithesh nambiar

    Hi,
    Problem might be with your query. Server exception error may occur while accessing large number data retrieving from the data base. It is execution type of error. What do you expect/want from your sql query?
    try this query
    SELECT ROW_NUMBER() OVER (ORDER BY CardName) AS RowNo,CardCode,CardName FROM OCRD Where CARDTYPE='C'
    Senthil Maruthappan.

Maybe you are looking for