PreparedStatement Synchronization Query

Hi All,
I hope this is the right place to post this query (heh)! In a Java Webapp I have around 30 PreparedStatement(s) stored as global variables. As it is possible that some of the PreparedStatement(s) will be executed by multiple users concurrently from different pages (i.e. sections of the code), in addition to the usual synchronization tags I have volatile boolean values to check whether a PreparedStatement is currently in use to prevent concurrent execution. For example:
//  PreparedStatement is global, ResultSet is local.
synchronized(this) {
  while (flagRaised) {
     try {
       wait();
     } catch (InterruptedException e) {
       // do nothing.
   flagRaised = true;
   try {
     preparedStatement.setString(1, "Pears");
     localResultSet = preparedStatement.executeQuery();
   } catch (SQLException e) {
     // log the problem
   flagRaised = false;
   notifyAll();
}I believe that this is necessary for any "mutator" statements where I'm using "setXXXX", but if I had a statement that returned an entire table would I need to implement any additional synchronization code? For example could I simply have:
localResultSet = preparedStatement.executeQuery(); // where the PreparedStatement returns a table.with no synchronization/volatile variables?
Thanks in anticipation,
Simon

I fail to see why the above is necessary. Think of what you are doing: caching a PreparedStatement. Why?
PreparedStatement, out of the box with a decent JDBC driver, will cache the parsed SQL query. Further, most RDBMS will also perform their own native cachine of query plans. (I will leave out the considerations of RDBMS cached execution plans, though they are also valid to the discussion). You are adding a level of pooling above and beyond what the vendor offers. This might be necessary if your own system, but have you benchmarked this? Do you 'know' the middleware parse of a PreparedStatement is your actual scaling bottleheck. IMO, this is a rare situation.
Rather, understand what both your RDBMS and your JDBC driver's use of PreparedStatement already offer you. Premature optimization is the root of most software evil, at least according to Knuth. Sure you are not contributing to the same?
- Saish

Similar Messages

  • PreparedStatement Object Query

    Hi,
    If i use the same PreparedStatement object for two queries, will it cause any issues.
    Example:
    //start program
    PreparedStatement ppt = null;
    ppt = some query;
    ppt.executeUpdate();
    if i try to use the same object for other query, will it cause any problem?
    ppt = anotherquery
    ppt.executeUpdate();
    //end program
    Thanks in Advance

    use same no problem
    but before this u have to store results in ResultSet objects
    so u have to create two ResultSet objects
    thank u

  • JDBC Call returns no results, SQL*Plus returns 1 record, Please help!

    Any help would be greatly appreciated.
    Running 9.2.0.5.0, and using latest 9.2 JDBC 1.4_g drivers in thin mode.
    Execute the following query from SQL*Plus and it returns one row, from JDBC using a PreparedStatement, I get no results. Here's the query, table def, record, etc.:
    Query:
    SELECT
    ID_WEB_FRM,ID_WEB_SIT,CDE_LVL_1_FUNC,
    CDE_LVL_2_FUNC,NUM_WEB_FUNC_PG,NUM_WEB_PG_ID
    FROM
    WEB_FRM
    WHERE
    ID_WEB_FRM = ' '
    OR
    (ID_WEB_SIT = 'test' AND CDE_LVL_1_FUNC = ' '
    AND CDE_LVL_2_FUNC = 'u2T' AND NUM_WEB_FUNC_PG = 1
    AND NUM_WEB_PG_ID = 0)
    Record returned from SQL*Plus:
    ID_WEB_FRM ID_WEB_SIT CDE CDE NUM_WEB_FUNC_PG NUM_WEB_PG_ID
    NfRRmc5XZu test u2T 1 0
    Both in the data returned and the query, there are no blanks, but they are a single space instead (hard to see in message here).
    Java code:
    int count = 1;
    findDBNameStatement.setString(count++," ");
    findDBNameStatement.setString(count++,form.getSiteID());
    findDBNameStatement.setString(count++," ");
    findDBNameStatement.setString(count++, form.getFunctionID());
    findDBNameStatement.setInt(count++,form.getPageNumber());
    findDBNameStatement.setInt(count++,form.getSectionNumber());
    ResultSet resultSet = findDBNameStatement.executeQuery();
    ResultSetMetaData metaData = resultSet.getMetaData();
    resultSet.next() returns false
    DB table:
    CREATE TABLE web_frm (
    ID_WEB_FRM varchar2(10) NOT NULL,
    ID_WEB_SIT varchar2(20) NOT NULL,
    NAM_WEB_FRM varchar2(40),
    TXT_EMAIL_SUBJ varchar2(50),
    CDE_LVL_1_FUNC char(3),
    CDE_LVL_2_FUNC char(3) NOT NULL,
    NUM_WEB_FUNC_PG int NOT NULL,
    NUM_WEB_PG_ID smallint NOT NULL,
    DTE_WEB_FRM_EFF date NOT NULL,
    DTE_WEB_FRM_TRM date,
    CDE_VLDT_RUL char(3),
    DTE_LAST_EXPRT date,
    TXT_CNFRMN_MSG varchar2(4000),
    IND_UPDT_ALWD char(1) NOT NULL,
    TXT_RECAP_HDR varchar2(4000),
    TXT_RECAP_FTR varchar2(4000),
    CDE_WEB_OBJ char(3),
    NUM_MAX_FRM_WIDTH number(4,0),
    IND_RECAP_PG char(1) NOT NULL,
    IND_CNFRM_PG char(1) NOT NULL,
    IND_DSPL_CNFRM_NUM char(1) NOT NULL,
    CNT_SUBM_MAX int,
    TXT_CHCE_ADD_MSG varchar2(255),
    TXT_CHCE_MOD_MSG varchar2(255),
    TXT_WEB_HDR varchar2(4000),
    TXT_WEB_FTR varchar2(4000),
    TXT_WAIT_LIST_MSG varchar2(255),
    FORMOBJECTHEIGHT int NOT NULL,
    FORMOBJECTWIDTH int NOT NULL
    ALTER TABLE web_frm ADD ( CONSTRAINT PK_web_frm PRIMARY KEY (ID_WEB_FRM));
    ALTER TABLE web_frm ADD ( CONSTRAINT UK_web_frm UNIQUE (ID_WEB_SIT,CDE_LVL_1_FUNC,CDE_LVL_2_FUNC,NUM_WEB_FUNC_PG,NUM_WEB_PG_ID)) ;
    Thanks,
    Matt

    I have verified the parameters and such, and if I run as a Statement instead of a PreparedStatement, the query works fine. After some more troubleshooting, I narrowed the problem down, but not sure of the fix.
    If I eliminate teh extra parameters and simplify things to:
    SELECT ID_WEB_FRM FROM WEB_FRM WHERE ID_WEB_SIT = 'test' AND CDE_LVL_2_FUNC = 'u2T' AND NUM_WEB_FUNC_PG = 1 AND NUM_WEB_PG_ID = 0
    The code works. But if I add the additional WHERE clause of CDE_LVL_1_FUNC = ' ' (has single space), it returns no data (record in the DB has single space in this new column. Query that does not work:
    SELECT ID_WEB_FRM FROM WEB_FRM WHERE ID_WEB_SIT = 'test' AND CDE_LVL_1_FUNC = ' ' AND CDE_LVL_2_FUNC = 'u2T' AND NUM_WEB_FUNC_PG = 1 AND NUM_WEB_PG_ID = 0
    It appears the JDBC Driver is trimming the parameter when it is a space when set through a PreparedStatement.setString(2," ")

  • Question about updateRow in ResultSet

    Simple problem. When I update the values in a resultset with:
    rs.updateString("columnName", aString);
    rs.updateRow();the value of columnName is updated, but the values of all the other columns in the row are set to nothing. How do I prevent this from happening? Do I have to update all the column values when using updateRow, i.e getting the values from the resultset and then updating with the same values?
    - Karl XII

    Hi Karl,
    You could try using the following code:
    int numRows = 0;
    int empId = 1223;
    String updateEmp="update employees set department=?
    where id = ?";
    PreparedStatement pstmt =
    conn.prepareStatement(updateEmp);
    pstmt.setString(1,"department");
    pstmt.setInt(2,empId);
    numRows = pstmt.executeUpdate();
    pstmt.close();
    This piece of code would only update the columns that
    you mention in the PreparedStatement SQL query.
    Thanks,
    Rashmi.Thanx. But I have a resultSet that is linked to the database. I to only like to edit the value of a specific column in the resultset... any other suggestions?

  • Character set mismatch with UTF-8

    I get character set mismatch error when attempting to run a JDBC PreparedStatement to query
    a table with primary key column of type NCHAR
    I'm using the thin 8i driver
    I'm using setString() to set the bind the parameter value to the statement
    Some of the documentation makes it sound like the driver will convert between character
    sets automatically. Other parts make it look like I should use the setCHAR() method of
    Oracle's OraclePreparedStatement class.
    Is there an easy way to do this ?

    I get character set mismatch error when attempting to run a JDBC PreparedStatement to query
    a table with primary key column of type NCHAR
    I'm using the thin 8i driver
    I'm using setString() to set the bind the parameter value to the statement
    Some of the documentation makes it sound like the driver will convert between character
    sets automatically. Other parts make it look like I should use the setCHAR() method of
    Oracle's OraclePreparedStatement class.
    Is there an easy way to do this ?

  • Controller Extension vs. AM Extension : Important

    Hi All,
    Keeping in view OAF seeded Page Customization Best Practice which is more advisable in the following scenario:
    (@Oracle Dev/Support guys: Please do provide arguments for/against. It would be helpful if u can point to any supporting Oracle Doc/metalink note )
    Requirement: Include User Input Validation Logic in a seeded page (validate values of custom DFF entered against an existing segment combination in a custom table)
    Solution Method1: Extending the region controller COSteps:
    1. Capture User Input
    2. Get current AM transactional object using
    ...//am is OAAplicationModule object
    OADBTransacton txn= am.getOADBTransaction();
    3. Use PreparedStatement to query the custom table
    4. Include data validation logic
    5. Point the region's controller to custom extended CO
    Solution Method2: Create a nw ViewObject and Extend the region AM to include validation logicSteps:
    1. Create VO for custom table
    2. Extend AM and include validation logic
    (The steps are just indicative and any other suggestions for solution is most appreciated. Also there is no need for any extra column/data to be shown or captured hence VO extension can b ruled out.)
    thanks
    --debashis                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Since your AM is not root AM, you can go ahead with AM extension.
    Only the extension of Root AM is not supported by OAF because of following issue
    OA Framework does not support substituting a root application module due to
    a known limitation in MDS and personalizations.
    A root application module substitution has no runtime effect in a deployed environment outside JDeveloper or
    could lead to a runtime error with a "Cannot Display Page" message in a LOV modal window in JDeveloper--Prasanna                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Mouse Double Click on an editable cell of JTable

    Hi Pros:
    Maybe this is an old question but no answser from Forum.
    I have a JTable with adding MouseListener. I tried to put double click behavior on nay row in the table. The problem was that this action can obly work on the uneditable cell and do not work on editable cell.
    Anyone have ideas and help me.
    Thank you!

    Hi Wang,
    I have a problem similar to the one you have some time back.
    I have a query for which I need to use PreparedStatement .The query runs likes this :-
    String str = " Select ? , ename from emp where deptno ? ";
    The values of ? need to be assigned dynamically.
    But I cannot create Prepared Statement from this query .
    If you have got answer to your questions can you inform me at
    [email protected]
    Thanks in advance

  • "Adobe Presenter is unable to initialize itself"

    When I lauch PowerPoint, this is the error message I get. Everything was working fine until recently. Adobe Presenter 7.0.6, PPT 2007, Dell Optiplex, Windows XP Pro.  Any ideas on how to fix this?
    Thanks,

    Would anyone know what could cause this?
    There were some errors in the Event Viewer, but nothing that would indicate the cause of this. they all seemed to be errors caused due to security.
    The one that I found to be most relevant reads:
    Event Type: Failure Audit
    Event Source:     Security
    Event Category:   Object Access
    Event ID:   560
    Date:       5/27/2009
    Time:       7:45:13 PM
    User:       <User ID>
    Computer:   D-0745345A
    Description:
    Object Open:
          Object Server:    Security
          Object Type:      Mutant
          Object Name:      \BaseNamedObjects\ZonesCounterMutex
          Handle ID:  -
          Operation ID:     {0,7531028}
          Process ID: 3696
          Image File Name:  C:\Program Files\Microsoft Office\OFFICE11\POWERPNT.EXE
          Primary User Name:      <User Name>
          Primary Domain:   ENTERPRISE
          Primary Logon ID: (0x0,0x2E9E9)
          Client User Name: -
          Client Domain:    -
          Client Logon ID:  -
          Accesses:         DELETE
                      READ_CONTROL
                      WRITE_DAC
                      WRITE_OWNER
                      SYNCHRONIZE
                      Query mutant state
          Privileges:       -
          Restricted Sid Count: 0
    For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.

  • String str = " Select ? , ...

    Hi ,
    I have a query for which I need to use PreparedStatement .The query runs likes this :-
    String str = " Select ? , ename from emp where deptno ? ";
    The values of ? need to be assigned dynamically.
    But I cannot create Prepared Statement from this query .
    If you have got answer to your questions can you inform me at
    Thanks in advance

    No, and you can't use a PreparedStatement where you have ? for the table name either. The database can't prepare it because it doesn't know what fields you will be asking for. So you will have to use a Statement and generate the SQL with string calculations. Sorry.

  • 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

  • Select IN query - PreparedStatement

    String val = "AAA','BBB','CCC','DDD";
    String query = "Select col1 from tabName where RTRIM(col2) in (?)"
    PreparedStatement p =conn.prepareStatement(query);
    p.setString(1,val);The above code doesn't return in value...Why?
    Using oracle DB, col2 is of type CHAR...

    First you should test that this returns values:String query = "Select col1 from tabName where RTRIM(col2) in ('AAA','BBB','CCC','DDD')";
    PreparedStatement p = conn.prepareStatement(query);Does it?
    Suppose it does then if you want to do a more dynamic statement you have to understand that JDBC does not support aggregated lists as single input parameter.
    You could do something like:String[] vals = { "AAA", "BBB", "CCC", "DDD" };
    String query = "Select col1 from tabName where RTRIM(col2) in (?,?,?,?)";
    PreparedStatement p = conn.prepareStatement(query);
    for (int i = 0; i < 4; i++)
        p.setString(i + 1, vals);Regards

  • Can I "see" the query string built by PreparedStatement?

    Hi all.
    When using a PreparedStatement, is there a way to see the SQL String built by the class, that is the query that's going to be executed by the "executeQuery()"?
    I'd need it for debugging reasons...
    Any help will be very appreciated!!

    http://www.javaworld.com/javaworld/jw-01-2002/jw-0125-
    overpower.htmlThis works great , that's was I was looking for.
    Thanks hermione!!
    I can't but recommend it to everyone that want to accomplish the same.

  • Hibernate Query vs PreparedStatement for SQL

    Hi,
    I am using Hibernate for DAO classes, which i am using for the basic CRUD operations. But for complex queries with complex joins i am writing the SQL.
    In such case whether it is better to use the Query.createSQLQuery(String sql) to invoke the SQL or better to use the PreparedStatement since i am invoking only the SQL as supposed to HQL by getting the connection from the Hibernate Session. Since the PreparedStatement is precompiled it may be faster than invoking the SQL through the Query.createSQLQuery(String sql)? or using the Session.getNamedQuery(QUERY_NAME)? Please let me know your opinion on this.
    Thanks

    Whether you use Hibernate, ODBC, BDE, or Funky Foo's SQL client library, Oracle does not give a damn.
    It receives a statement from the client. This can either be SQL or an anonymous PL/SQL block. It parses it as a cursor. It then provides the client with a cursor handle to reference the cursor.
    The cursor is essentially a program. If it has bind variables, it is a program that accepts parameter input. This allows the very same program to be executed multiple times with different input parameters. For example, executing the same INSERT SQL cursor for different values and inserting multiple rows using the very same cursor.
    A cursor can also (like a program), produce output. An example is a SELECT cursor - where the fetch interface of the cursor enables the caller to consume the output of the cursor.
    So what is optimal in this respect? First and foremost cursors that are created using and used with bind variables. Secondly, re-using the very same client cursor handle (and not just the same server side SQL cursor) where possible (e.g. like repeating the same SQL INSERT statement with different values).
    The question to asked is whether the method you select to use on the client side - be that Hibernate or Funky Foo SQL, support this?
    The consideration to make is the following. Why code SQL in the client side? SQL is executed on the server-side - refers to server side data structures and needs to be tuned on the server. Put that code in a client and it significantly increases the complexity and decrease the flexibility of SQL.
    The alternative (and recommended approach) is to use PL/SQL to encapsulate all SQL. Instead of the client (and client programmer) needing to know SQL, a PL/SQL call interface is provided with calls like GetInvoice() to return a single specific invoice, or GetInvoiceByDate() that returns selected invoices for a date range. The PL/SQL code creates the SQL cursor and returns the client cursor handle as a reference cursor to the caller.
    This also allows business and validation logic to be implemented in the PL/SQL call interface to protect data integrity and business transaction sanity. A database structure change requires the SQL inside a PL/SQL procedure to be changed - without having to touch the client code. Likewise, SQL can be tuned and improved without having recompile a single byte of client code. And the same PL/SQL call interface services all clients - unlike multiple Java clients duplicating the same SQL (and not always correctly) to do the same thing, or having to duplicate and repeat the same data validation and business rule logic.

  • Query on synchronization

    Hi,
    I have a query on synchronization. When an object is accessed by two or more threads simultaneously, we use the synchronize keyword to prevent two threads simultaneos access. So on which this lock is obtained either it is on the object or the synchronized methods.
    chetana

    The lock is obtained for the object as a whole. Actually each object has it's associated Monitor, and every time a thread accesses a synchronized method on an object, it gains that objects' monitors' lock. While a thread owns a lock on an objects' monitor, no other thread can access that objects' synchronized methods.

  • Does Toplink Database query use PreparedStatement by default

    Hi
    I would like to know when we invoke a ReadAllQuery/ReportQuery by constructing a toplink expression, does toplink internally translate that into a PreparedStatement, bind the variables to the specified values and then execute the actual DB query ?

    A prepared statement can be cache, and re-executed with different bind parameters. This saves the database from having to re-parse the SQL, so can provide the database a performance advantage. The degree of this benefit varies with database and version, but it can be significant in cases.
    By default TopLink uses prepared statements, but does not cache them. This is mainly because with JEE DataSources TopLink does not have control over the connection, so the DataSource must perform the statement caching. Most DataSources support this (but most not by default). Some older JDBC drivers may also have issues with caching statements.
    TopLink fully supports caching prepared statements, this can easily be enabled as an option on the TopLink DatabaseLogin.setShouldCacheAllStatements(), or sessions.xml, or JPA persistence.xml property "toplink.jdbc.cache-statements" or "eclipselink.jdbc.cache-statements".

Maybe you are looking for

  • Ever since updating to IOS 6, my wifi has not been staying connected

    This is applicable for my iPad and iPhone 4S. My iPhone doesn't connect to my home wifi at all and my iPad has issues staying connected. I never have these issues using my work place's free wifi for either device. At home I lose connection with my Wi

  • Problems with the width of my page created in adobe muse (scrolled)

    I have a little problem I get a small scroll (scrolled) in the page to move sideways and do not know how to remove it and do not know why I get and I spoil that little scroll whole layout of the page. Please watch this short video and live shows. Vid

  • Does keynote 09 work with iCloud?

    I can't seem to get Keynote to sync in icloud. It is the '09 version. Do I need to download the $9.99 app from the app store...is that a version that would work?

  • Use event function for multiple events

    I've got several movieclip buttons on stage. For one of those buttons I've started of with: button1.buttonMode = true; button1.useHandCursor = true; button1.addEventListener(MouseEvent.MOUSE_DOWN, fl_ClickToDrag); function fl_ClickToDrag(event:MouseE

  • ASA5520 Routing/Subnet Configuration Help

    Hi, I'm not much of a networking guy and need some help getting my ASA5520 to play ball. The general gist is that I have 3 subnets (xxx.xxx.1.xxx, xxx.xxx.2.xxx, and xxx.xxx.5.xxx), two of them (.1 and .2) are on ASA1 and can see each other fine. One