PreparedStatement.setArray

Hello,
I'd like to use a preparedstatement to perform a query like this:
select * from requests where id_request in ( ? )
I've tried to do
pstmt.setArray(1, "1, 2, 3"); but it doesn't work.
Does anyone know how to do this?

Hello,
Thanks, but there is no exemple on that page for
- setArray
or
- "select * from x where id in (?)"
One solution would be to create the full query in a String and then execute that, but I wanted to use a preparedstatement and a ? parameter.
Ex.:
public void runSelect(String param){
String sql = "select * from x where id in (" + param + ")";
resultset = statement.executequery(sql);
What I wanted was something more like:
public void runSelect(String param){
String sql = "select * from x where id in (?)";
prepStatement = conn.prepare(sql);
prepStatement.setObject(1, param); //setObject or setArray or something
resultset = statement.executequery();
}

Similar Messages

  • PreparedStatement.setArray() ... again

    Hi Joe;
    I am aware that weblogic pool driver does not support Oracle Array's
    via .setArray. This is because Oracle Array's require
    ArrayDescriptor, and when I call this class with a Weblogic Pool
    Connection, a ClassCastException is thrown because the Connection
    object is not an OracleConnection.
    Is there anyway I can use PreparedStatement.setArray() without
    getting this ClassCastException? Are there any known workarounds that
    prevents me from having to use Oracle Specific classes?
    I am using WLS 6.1sp4 on Oracle 9i
    Thanks,
    [email protected]

    Paul Rowe wrote:
    Hi Joe;
    I am aware that weblogic pool driver does not support Oracle Array's
    via .setArray. This is because Oracle Array's require
    ArrayDescriptor, and when I call this class with a Weblogic Pool
    Connection, a ClassCastException is thrown because the Connection
    object is not an OracleConnection.
    Is there anyway I can use PreparedStatement.setArray() without
    getting this ClassCastException? Are there any known workarounds that
    prevents me from having to use Oracle Specific classes?
    I am using WLS 6.1sp4 on Oracle 9iHi. In 6.1sp5 we implement a method on pool connections, getVendorConnection(),
    which for those intractible cases where Oracle secretly requires a specific class
    (it's secret because the method signatues says it takes a java.sql.Connection),
    we provide a way to get a direct reference to the pooled oracle connection.
    This is dangerous, because it gives application code a backdoor to the pooled
    resource, and we can never again guarantee that future pool users are getting
    sole access to the connection. Therefore, by default we will close and replace
    any pooled connection after it is exposed in this way. Read the docs on this option,
    and I can give advice too on the safe things to do with an exposed connection,
    and later, how to retrieve the performance lost to the pool having to replace
    exposed connections....
    Joe
    >
    >
    Thanks,
    [email protected]

  • Oracle, SELECT IN and PreparedStatement.setArray

    I want to execute the following query: SELECT * FROM SOMETABLE WHERE IDFIELD IN (?)
    The number of values in the IN list is variable. How can I do this with a prepared statement?
    I am aware of the different alternatives:
    1) Keep a cache of prepared statement for each sized list seen so far.
    2) Keep a cache of prepared statements for different sizes (1, 5, 10, 20) and fill in the left over parameter positions with the copies first value.
    They both have the disadvantage that there could be many prepared statements for each query that get used once, and never used again.
    I have tried this:
    stmt.execute ("CREATE OR REPLACE TYPE LONGINTLIST AS TABLE OF NUMBER(15)");
    ArrayDescriptor desc = ArrayDescriptor.createDescriptor ("LONGINTLIST", conn);
    long idValues [] = {2, 3, 4};
    oracle.sql.ARRAY paramArray = new oracle.sql.ARRAY (desc, conn, idValues);
    PreparedStatement query = conn.prepareStatement ("SELECT * FROM MYTABLE WHERE ID_FIELD IN (?)");
    query.setArray (1, paramArray);
    But Oracle gives a data conversion error.
    I then tried this:
    PreparedStatement query = conn.prepareStatement ("SELECT * FROM MYTABLE WHERE ID_FIELD IN (SELECT * FROM TABLE (?))");
    This works and the rows are returned, but the Oracle optimizer does not like it very much, since it always does a full table scan even though there is a primary key index on ID_FIELD.
    Any ideas?
    I also tried this:
    OraclePreparedStatement oraQuery = (OraclePreparedStatement) query;
    oraQuery.setARRAY (1, paramArray);
    But same behavior.
    Roger Hernandez

    Please re-read the original message. As I mentioned,
    I am aware of the two commonly used alternatives.No actually the most used alternative is to build the SQL dynamically each time.
    I know how to get both of them to work, and have used
    both alternatives in the past. The downside to both
    these approaches is that you need to save multiple
    prepared statements for each query. What I am trying
    to find is a way of having only one saved prepared
    statement for a query having a variable number of IN
    clause parameters.You could probably use a stored procedure that takes an 'array' and then do the processing in the stored proc to handle each array element.
    However, your database might not support that stored procs or arrays. Or it might not cache it with arrays. And the overhead of creating the array structure or processing it in the proc might eat any savings that you might gain (even presuming there is any savings) by using a prepared statement in the first place. Of course given that you must be using an automated profiling tool and have a loaded test environment you should be able to easily determine if this method saves time or not.
    Other than that there are no other solutions.

  • Java.sql.PreparedStatement.setArray( ) not found in J2SE v1.3.1?

    Why do I get the error method setArray(int, Array) not found in interface java.sql.PreparedStatement? As per on-line documentation the method is available since version 1.2.
    In JDeveloper help I have read that...
    "JDeveloper uses J2SE definitions to describe an installed J2SE environment. This environment can be either a JRE (Java Runtime Engine) or an SDK. Note that if you are using a JRE, some features may not be available. Every JDeveloper project uses a J2SE definition to determine what version of the Java API to compile and run with."
    Is my problem because my JDeveloper installation is using a JRE and not an SDK?

    Sounds like a SQL problem. Not an expert in DB2 bu you might want to try INSERT INTO SESSION (col1name, col2name) VALUES (?,?);
    Edited by: Kungen on Sep 19, 2007 6:46 AM

  • SetArray and PreparedStatement

    Is it possible to use setArray with a PreparedStatement (or setARRAY and OraclePreparedStatement, or anything else similar) to enable use of prepared statements in the situation where the query looks something like this:
    SELECT *
    FROM some_table
    WHERE some_field IN ( ? );
    where the number of elements in the set of the IN clause can vary on each execution?
    Hope I've explained myself properly.
    Thanks.

    I think you can.
    Refer to this document for more information on how to use it.
    http://download-west.oracle.com/docs/cd/B10501_01/java.920/a96654/oraarr.htm#1040124
    Regards,
    Anupama

  • SetArray of PreparedStatement

    Can any one tell me how the setArray is used in PreparedStatement where in the Query takes 2 parameters. Now the requirement is that instead of me running the SQL in loop for different values, I just want to set the array using setArray method of PreparedStatement.
    Snippet of code will be of a great help.

    u cant do it.
    setArray() method is for setting a 'array' value the prepared statement. it is very much similar to setInt(index, intValue) or setString(index,StringValue) methods.
    Array is thehe mapping in the Java programming language for the SQL type ARRAY.

  • Cannot insert String[] objects in PreparedStatements !!!

    Hello guys,
    I'm using PostgreSQL 7.0.3 for a website project.
    I've got a table in the website database system which has a integer array type,
    e.g.
    create table preferences(
    user_id integer references user,
    music varchar(20)[5],
    magazines varchar(20)[5],
    channel varchar(10)[3]
    )I've also got an javabean which holds the use preferences object
    public class userPref{
    private String[] music;
    private String[] magazines;
    private String[] channel;
    private int userId;
    // a constructor which uses reflection
    public userPref(HttpServletRequest request){
    }know i would like to be able to insert some values in that
    table using java.sql library.
    i've got
    Connection con = broker.getConnection(); // the connection pool releases one connection
    PreparedStatement ps = con.prepareStatement;
    ps.setInt(1,user.getId());
    ...But for the rest of the fields, what should I use ?
    I saw that there was setArray method in the PreparedStatement that uses java.sql.Array Class
    Is it the method that I've got to use. If so, do I need to implement it ?
    Please help me,
    touco

    I have no idea if that is the method you have to use or whether it will do what you want, but you do not have to implement it. That is the responsibility of the JDBC driver writer, just like the other 100-odd methods of PreparedStatement.

  • ARRAY using in PreparedStatement in various servers

    Hello, all! I have a question.
    I want to use array in my sql query and write next:
    PreparedStatement ps = con.prepareStatement(MY_QUERY);
    ArrayDescriptor arrayDescriptor = ArrayDescriptor.createDescriptor("CHAR_ARRAY", wrappedConection);
    ARRAY myArray = new ARRAY(arrayDescriptor, con, javaArray);
    ps.setArray(1, myArray);
    ResultSet result = ps.executeQuery();
    The problem lay in the arrayDescriptor need for OracleConnection, but I have wrapped connection from various servers. Any suggestions?

    If you need a database-specific class that's outside the java.sql interface set, I'd say you're doing it wrong.
    How is saving an array relational? Why wouldn't it be n records instead of 1?
    %

  • SetArray Method

    Hi,
    I am trying to update Array datatype in Oracle.
    I am getting java.sql.Array object from database since I can't create descriptor
    from
    weblogic pool using JNDI.
    Now I have this Array but its just a pointer, How can I update values in this
    array.
    here is the code
    ... after creating connection
    Array array=null;
    while (rs.next()){
    array = rs.getArray("myarray");
    String[] mystringarray = (String[])array.getArray();
    for (int i = 0; i < mystringarray.length; i++) {
    scores="student no." + i;
    However I need to know how to update this Array?
    I want to call --
    PreparedStatement pstmt =                          conn.prepareStatement("{call test_package.newarray(?)}");
    pstmt.setArray(1, array);
    pstmt.executeUpdate();
    If I cannot update this way bec its a pointer to recordset, how do I go about
    updating?
    thanks

    Actually you are not using OracleConnection's createARRAY method. Your code says 'cstmt.createARRAY' and cstmt is presumablyl a calleable statement.Hard to see how that could be so given that there is no CallableStatement.createArray() method, nor even an OracleCallableStatement.createArray() method. The only createArray() method mentioned in the document you cited is in OracleConnection.

  • How to print Integrity sql in the preparedstatement?

    How to print Integrity sql in the preparedstatement?
    Connection conn = null;
    String sql = "select * from person where name=?";
    PreparedStatement ps = conn.prepareStatement(sql);
    ps.setObject(1, "robin");
    ps.executeQuery();
    i'm wants print Integrity sql.
    For example:select * from person where name='robin'
    How should I do?
    thanks a lot!

    PreparedStatement doesn't offer methods for that. You can write your own implementation of PreparedStatement which wraps the originating PreparedStatement and saves the set* values and writes it to the toString().
    If needed, myself I just print the sql as well as the values-being-set to the debug statement.Logger.debug(query + " " + values);

  • PreparedStatement not working

    Hi,
    I am having some problem using PreparedStatement.executeUpdate() . I want to be able to prepare several queries before commiting and I wrote this just to test it
    PreparedStatement stmt= aConnection.prepareStatement("update trans_test1 set field1='a text field' where field1='other text'");
              stmt.executeUpdate();
              aConnection.commit();
              stmt.close();
              aConnection.close();
    when it hits this line "stmt.executeUpdate();" the program just stops running and after a while throws this error.
    java.sql.SQLException: Lock wait timeout exceeded; try restarting transaction
    I set the auto commit to false but I still can't get it working and do not understand the problem. Any one can help?
    Thanks so much
    Alejo

    Hi,
    I am having some problem using
    PreparedStatement.executeUpdate() . I want to be able
    to prepare several queries before commiting and I
    wrote this just to test it
    PreparedStatement stmt=
    aConnection.prepareStatement("update trans_test1 set
    field1='a text field' where field1='other text'");
              stmt.executeUpdate();This is wrong in so many ways:
    (1) Use the bind variables.
    (2) Close resources properly in a finally block.
    (3) You don't show where you set auto commit to false
    (4) You don't show where you rollback in the event of a failure.
    >
    I set the auto commit to false but I still can't get
    it working and do not understand the problem. Any one
    can help?A snippet like this isn't enough. Post all the code.
    Which database are you using, and which driver?
    %

  • Problem with PreparedStatement

    I'm using a statement which needs to determine if the value is in a group.
    The statement will be
    "select name,age,occupation from personnel where age in ?"
    ps.setString(1, "(20,21,22)");
    I've also tried
    ps.setString(1, "('20','21','22')");
    Neither brings back any values in the result set.
    I can't figure out how to print what the preparedstatement looks like after setting the value.
    I look in the table and there are records with age 20, 21, 22.. and age is set as a string.

    Try this:
        query_B = "select tablename.blah_blah_blah"
                + "  from tablename"
                + " where tablename.etc is null"
                + "   and table.blah_term_code       in (?, ?)"
                + " order by 1, 2, 4, 7";
          String[] in_sem_dt = { "200307", "200308" };
          pstmt_B = con.prepareStatement( query_B );
          pstmt_B.setString( 1, in_sem_dt[0] );
          pstmt_B.setString( 2, in_sem_dt[1] );
          rs_B = pstmt_B.executeQuery();~Bill

  • Closing PreparedStatements & ResultSets

    Is it necessary to explicitly close ResultSet AND PreparedStatement objects when used together? For example:
    PreparedStatement ps;
    ResultSet rs;
    String sql = " SELECT * FROM some_table WHERE id = ? ";
    try {
        ps = connection.prepareStatement(sql);
        ps.setString(1, someId);
        rs = ps.executeQuery();
        // And so on.....
    } finally {
      rs.close();
      ps.close();
    }Is it sufficient to close only the PreparedStatement? Does the ResultSet get cleaned up automatically when the PreparedStatement is closed? I don't want any lingering cursors left open, but at the same time, I don't want to write code that isn't needed. What's considered best form?
    Thanks.
    BTW: I'm using Oracle 8i/9i.

    I always close a Statement object, but don't worry about the ResultSet...that's really just a matter of redundancy...
    From the API on Statement.close()
    Note: A Statement object is automatically closed when it is garbage collected. When a Statement object is closed, its current ResultSet object, if one exists, is also closed.

  • Too many connections - even after closing ResultSets and PreparedStatements

    I'm getting a "Too many connections" error with MySQL when I run my Java program.
    2007-08-06 15:07:26,650 main/CLIRuntime [FATAL]: Too many connections
    com.mysql.jdbc.exceptions.MySQLNonTransientConnectionException: Too many connections
            at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:921)
            at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2870)
            at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:812)
            at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:3269)
            at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1182)
            at com.mysql.jdbc.Connection.createNewIO(Connection.java:2670)I researched on this and found out that I wasn't closing the ResultSet and the PreparedStatement.
    The JDBC connection is closed by a central program that handles connections (custom connection pooling).
    I added the code to close all ResultSets and PreparedStatements, and re-started MySQL as per the instructions here
    but still get "Too many connections" error.
    A few other things come to mind, as to what I may be doing wrong, so I have a few questions:
    1) A few PreparedStatements are created in one method, and they are used in a 2nd method and closed in the 2nd method
    does this cause "Too many connections" error?
    2) I have 2 different ResultSets, in nested while loops where the outer loop iterates over the first ResultSet and
    the inner loop iterates over the second ResultSet.
    I have a try-finally block that wraps the inner while loop, and I'm closing the second ResultSet and PreparedStement
    in the inner while loop.
    I also have a try-finally block that wraps the outer while loop, and I'm closing the first ResulSet and PreparedStatement
    in the outer while loop as soon as the inner while loop completes.
    So, in the above case the outer while loop's ResultSet and PreparedStatements remain open until the inner while loop completes.
    Does the above cause "Too many connections" error?
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    The following is relevant sections of my code ( it is partially pseudo-code ) that shows the above 2 cases:
    init( Connection jdbcConnection ){
       String firstSQLStatement = "....";
       PreparedStatement ps1 = jdbcConnection.prepareStatement( firstSQLStatement );
       String secondSQLStatement = "....";
       PreparedStatement ps2 = jdbcConnection.prepareStatement( secondSQLStatement );
       String thirdSQLStatement = "....";
       PreparedStatement ps3 = null;
       ResultSet rsA = null;
       try{
            ps3 = jdbcConnection.prepareStatement( thirdSQLStatement );
            rsA = ps3.executeQuery();
            if( rsA.next() ){
                   rsA.getString( 1 );
       }finally{
            if( rsA != null )
                   rsA.close();
            if( ps3 != null )
              ps3.close();
       //Notice, how ps1 and ps2 are created here but not used immediately, but only ps3 is
       //used immediately.
       //ps1 and ps2 are used in another method.
    run( Connection jdbcConnection ){
         ResultSet rs1 = ps1.executeQuery();
            try{
               while(rs1.next()){
                    String s = rs1.getString();
                    ps2.setString(1, s);
              ResultSet rs2 = ps2.executeQuery();
                    try{
                   while(rs2.next()){
                        String s2 = rs2.getString();
                    }finally{
                   if( rs2 != null )
                     rs2.close();
                   if( ps2 != null )
                     ps2.close();
         }catch( Exception e ){
              e.printStackTrace();
         }finally{
            if( rs1 != null )
                  rs1.close();
               if( ps1 != null )
                  ps1.close();
    //Notice in the above case rs1 and ps1 are closed only after the inner
    //while loop completes.
    }I appreciate any help.

    Thanks for your reply.
    I will look at the central connection pooling mechanism ( which was written by someone else) , but that is being used by many other Java programs others have written.
    They are not getting this error.
    An addendum to my previous note, I followed the instructions here.
    http://dev.mysql.com/doc/refman/5.0/en/too-many-connections.html
    There's probably something else in my code that is not closing the connection.
    But I just wanted to rule out the fact that opening a PreparedStatement in one method and closing it in another is not a problem.
    Or, if nested ResultSet loops don't cause the problem.
    I've read in a few threads taht "Too many connections" can occur for unclosed RS and PS , and not just JDBC connections.

  • Memory problems with PreparedStatements

    Driver: 9.0.1 JDBC Thin
    I am having memory problems using "PreparedStatement" via jdbc.
    After profiling our application, we found that a large number oracle.jdbc.ttc7.TTCItem objects were being created, but not released, even though we were "closing" the ResultSets of a prepared statements.
    Tracing through the application, it appears that most of these TTCItem objects are created when the statement is executed (not when prepared), therefore I would have assumed that they would be released when the ResultSet is close, but this does not seem to be the case.
    We tend to have a large number of PreparedStatement objects in use (over 100, most with closed ResultSets) and find that our application is using huge amounts of memory when compared to using the same code, but closing the PreparedStatement at the same time as closing the ResultSet.
    Has anyone else found similar problems? If so, does anyone have a work-around or know if this is something that Oracle is looking at fixing?
    Thanks
    Bruce Crosgrove

    From your mail, it is not very clear:
    a) whether your session is an HTTPSession or an application defined
    session.
    b) What is meant by saying: JSP/Servlet is growing.
    However, some pointers:
    a) Are there any timeouts associated with session.
    b) Try to profile your code to see what is causing the memory leak.
    c) Are there references to stale data in your application code.
    Marilla Bax wrote:
    hi,
    we have some memory - problems with the WebLogic Application Server
    4.5.1 on Sun Solaris
    In our Customer Projects we are working with EJB's. for each customer
    transaction we create a session to the weblogic application server.
    now there are some urgent problems with the java process on the server.
    for each session there were allocated 200 - 500 kb memory, within a day
    the JSP process on our server is growing for each session and don't
    reallocate the reserved memory for the old session. as a work around we
    now restart the server every night.
    How can we solve this problem ?? Is it a problem with the operating
    system or the application server or the EJB's ?? Do you have problems
    like this before ?
    greetings from germany,

Maybe you are looking for

  • Error while activating the form

    when i was activating the form iam getting an error INVALID  HTTP Connection ADS. please give me a solution. Thanks&Regards Siva

  • WBS Element settlement error

    Dear All My query is the prj is EP & WBS El is EP-99, under EP-99 the avialable values are Rs192,523/- as per different cost element wise. Those values have to settled on an one AUC-asset & the value will be settled periodicaly. My posted values are

  • Can I download 'Mountain Lion'within a few weeks, when available, without downloading 'Lion' first? I'm still working with 'Snow Leopard.

    Can I download Mountain Lion' when available without downloading 'Lion' first? I'm still working with 'Snow Leopard'.

  • IPhone 3G goes black screen

    this morning I was checking my email and my phone froze up, so I held the home button and top button together to restart it. it actually powered down instead of giving me the red reboot option. I then clicked the home button to start it up again, and

  • SOLARIS 2.6 logical IP limit

    good day! i hope you guys can help me out with my problem... i need it coz i next week is my deadline... i'm researching about the maximum number of logical IPs can Solaris 2.6 (SunOS 5.2) support... in Solaris 2.5.1 i can only add 255 logical IPs us