PreparedStatement question

If I have a PreparedStatement, and I want to pass in a dynamic table name, can I accomplish that:
PreparedStatement ps = conn.prepareStatement("SELECT * FROM " + tableName + ";");
ps.setString(1, "DINNERTABLE");
Thanks,
Lior

In a prepared statement the host variable is indicated by using a "?" in the proper position (i.e. instead of your "tableName" variable).
I do not know if it works with the table name, though.
Bye

Similar Messages

  • Resultset, preparedstatement question. what is first..

    Hello.
    My English ability is very poor. sorry
    Usually
    I did...
    Rs.close();
    pstmt.close();
    con.close();
    but
    pstmt.close();
    rs.close();
    con.close();
    is it possible....
    have no error but I want know. If resultset is alive, preparedstatement can close?
    Q 2.
    I use DBConnectionManager
    but it is nullpointer exception
    In my book
    rs.next();
    } finally {
    if (rs != null) rs.close();
    if (pstmt != null) pstmt.close();
    if(con!=null) connMgr.freeConnection("mysql",con);
    } <-- it's not close con(Connection)
    but in my another book
    con.close();
    what is correct?

    Hello.
    My English ability is very poor. sorry
    Usually
    I did...
    Rs.close();
    pstmt.close();
    con.close();
    but
    pstmt.close();
    rs.close();
    con.close();
    is it possible....
    have no error but I want know. If resultset is alive,
    preparedstatement can close?
    No. Once the statement is closed (regardless of type) the ResultSet can not be used.
    You should explicitly close everything and make sure that the result set is closed first.
    >
    Q 2.
    I use DBConnectionManager
    but it is nullpointer exception
    In my book
    rs.next();
    } finally {
    if (rs != null) rs.close();
    if (pstmt != null) pstmt.close();
    if(con!=null) connMgr.freeConnection("mysql",con);
    } <-- it's not close con(Connection)
    but in my another book
    con.close();
    what is correct?
    You are looking at two different things. In the first example it is using connection pool. The freeConnection() method returns the connection to the connection pool. In the second example there is no connection pool, so the connection must be explicitly closed.

  • PreparedStatement general questions

    I've been looking high and (not too) low for a definitive answer for this. Of course, not finding what I want to hear, I assume I'm looking in the wrong place...
    Is there an advantage to using PreparedStatement (vs. Statement) when there are no variables in the query?
    Possibly another way of getting at the same info:
    Is a PreparedStatement query in the shared pool shared by all users, or is there a shared pool for each user, each with his own set of parsed statements (I'm specifically talking about Oracle)?
    The reason I ask the second question is that, since my query doesn't have variables, even as a Statement object, it will be identical each time it's executed, so Oracle won't parse it again, correct? But that's not what I'm seeing.
    Thanks!
    Bryan

    jbisotti is right. The PreparedStement statement cached ( which is the correct terminology, pooling suggesting exclusive use, whereas cache imply shared usage) per connection.
    Oracle has two schemas for caching PreparedStatements
    Explicit - User identifies each statement by a unique key when storing
    it to cache. This key is later used to retrieve the statement
    for use. Faster
    Implicit - User sumply create the statement, internal functionality
    takes care of the rest
    Go to Oracle site to find out more. You will find code samples for both
    approaches
    Code snippet for Implicit approach
        // Enable connection for caching
             con.setStmtCacheSize(size, true);
        // Get current size of cache
              int  size =  con.getStmtCacheSize();
       Note: Once the connection is closed, the caching is lost

  • 2 questions in PreparedStatement in JSP

    Dear All,
    I got 2 questions in PreparedStatement in JSP that i can't solve
    Q1) when I m inserting a record that contains \r\n then the PreparedStatement will replace it into \\r\\n.
    Q2)I can't insert records when it contains ' by using PreparedStatement.
    How can i resolve these problems
      public int updateInterview(int interviewID,String interviewee,String interviewer,String i_date,String i_time,String summary,String photo_path,String update_staff,String content,String person_title,String i_type) {
      Interview interview = new Interview();
      InterviewDAO dao = new InterviewDAO();
        interview.setInterviewID( interviewID );
        interview.setInterviewer( interviewer );
        interview.setInterviewee( interviewee );
        interview.setInterviewDate( i_date );
        interview.setInterviewTime( i_time );
        interview.setSummary( summary );
        interview.setPhotoPath( photo_path );
        interview.setUpdateStaff( update_staff );
        interview.setContent( content );
        interview.setPersonTitle( person_title );
        interview.setIntervieweeType( i_type );
        return dao.updateInterview(interview);
      }

    public int updateInterview(Interview interview) {
    int updateCount = 0;
    try{
    sql = "update interview set interviewee=?, interviewer=?, i_date=?, i_time=?, summary=?, photo_path=?, update_date=now(), update_staff=?, content=?, person_title=?, i_type=? ";
    sql += "where interviewID=?";
    Connection conn = db.getConnection();
    PreparedStatement pstm = conn.prepareStatement(sql);
    int i = 1;
    pstm.setString(i++,interview.getInterviewee());
    pstm.setString(i++,interview.getInterviewer());
    pstm.setString(i++,interview.getInterviewDate());
    pstm.setString(i++,interview.getInterviewTime());
    pstm.setString(i++,interview.getSummary());
    pstm.setString(i++,interview.getPhotoPath());
    pstm.setString(i++,interview.getUpdateStaff());
    pstm.setString(i++,interview.getContent());
    pstm.setString(i++,interview.getPersonTitle());
    pstm.setString(i++,interview.getIntervieweeType());
    pstm.setInt(i++,interview.getInterviewID());
    updateCount = pstm.executeUpdate();
    conn.close();
    catch(SQLException sql){}
    return updateCount;
    }

  • A question about PreparedStatement and ORA-03115 error

    Dear all,
    I have an issue with JDBC and I would appreciate if you could kindly give me a hand.
    I'm using:
    - Oracle Database 11g Enterprise (Release 11.1.0.6.0)
    - JDBC thin driver version: ( 11.1.0.7.0-Production)
    - JDK 1.6
    - Operating system: Linux (Ubuntu 8.10)
    Here is my code
    import java.sql.*;
    public class Main
        public static void main(String[] args)
            String dbURL = "jdbc:oracle:thin:@localhost:1521:mydatabase";
            String username = "scott";
            String user_password = "tiger";
            try
                Connection connection = DriverManager.getConnection(dbURL, username, user_password);
                String query_text = "SELECT * FROM mytable";
                Statement statement = connection.createStatement();
                ResultSet query_result = statement.executeQuery(query_text);
                connection.close();
            catch (SQLException e)
                for (Throwable t: e)
                    t.printStackTrace();
    }This works pretty well without any problem. But when I want to use PreparedStatement instead of Statement I receive the ORA-03115 error message, that is, when I replace the Statement with PreparedStatement in the following way:
    String query_text =
            "SELECT first_name, ?, id, ?, job_title, salary  FROM mytable "+
            "WHERE id IN ('id14', ?, 'id17', 'id18')";
    PreparedStatement prepared_statement =  connection.preparedStatement(query_text);
    prepared_statement.setString(1, "last_name");
    prepared_statement.setString(2, "birthday");
    prepared_statement.setString(3, "id02");
    ResultSet query_result = prepared_statement.executeQuery(query_text);I get the following:
    java.sql.SQLException: ORA-03115: unsupported network datatype or representation
         at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:70)
         at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:133)
         at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:206)
         at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:455)
         at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:413)
         at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:1034)
         at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:194)
         at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:791)
         at oracle.jdbc.driver.T4CPreparedStatement.executeMaybeDescribe(T4CPreparedStatement.java:866)
         at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1186)
         at oracle.jdbc.driver.OracleStatement.executeQuery(OracleStatement.java:1377)
         at oracle.jdbc.driver.OracleStatementWrapper.executeQuery(OracleStatementWrapper.java:387)
         at mysqlpackage.Main.main(Main.java:33)Therefore, right after
    ResultSet query_result = prepared_statement.executeQuery(query_text);the exception is thrown,
    why it works with Statement but not with PreparedStatement? I tested with several other queries, insert a new row, delete a row, everytime it works well, but when I want to use PreparedStatement instead of Statement, again I have this error message.
    Any idea?
    Thanks in advance,

    OK, I found myself the answer.
    First error, I had use ? also for column names, which is not accepted as the SQL query has to be precompiled.
    Second error: Instead of writing
    ResultSet query_result =  prepared_statement.executeQuery(query_text);I had to write:
    ResultSet query_result =  prepared_statement.executeQuery();I tested with the following
    String query_text =
                  "SELECT first_name, last_name, id, birthday, job_title, salary "+
                  "FROM myenterprise "+
                  "WHERE id IN (?, ?, ?, ?) ";
                PreparedStatement prepared_statement =
                        connection.prepareStatement(query_text);
                prepared_statement.setString(1, "id02");
                prepared_statement.setString(2, "id04");
                prepared_statement.setString(3, "id08");
                prepared_statement.setString(4, "id09");
                ResultSet query_result =  prepared_statement.executeQuery();And it works pretty well now! :)

  • Easy Question about PreparedStatement

    Hi Everyone,
    I have a prepared statement. like this
    "INSERT INTO Accounts VALUES(" +
    "SeqAccountId.nextval" + ",?,?,?,?,?,?,?,?)";
    dbStatement = dbCon.prepareStatement(sqlStatement);
    dbStatement.clearParameters();
    dbStatement.setInt(1,paymentMethodId);
    dbStatement.setString(2,accountName);
    dbStatement.setInt(3,accountTypeId);
    dbStatement.setTimestamp(4,createDate);
    dbStatement.setTimestamp(5,expirationDate);
    dbStatement.setString(6,status);
    dbStatement.setInt(7,Modifiedby);
    dbStatement.setString(8,notes);
    If I were not to set the value for one of the question marks would it give me error or would it just insert a null value ?? ???
    Thanks
    Stephen

    Stephen,
    This will result in an SQL error of "not all variables bound" type.
    Regards,
    Neill Horton

  • Conceptual question regarding PreparedStatement

    Hi all,
    I wonder what is the different between the following 2 codes:
        public void method1(String[] cityList) throws Exception
             for (int x=0; x<cityList.length; x++)
                  String q="SELECT * FROM table 1 WHERE CITY='"+cityList+"'";
                      Statement stmt = con.createStatement();
                      ResultSet rs = stmt.executeQuery(q);   
                      while (rs.next())
                           //some code here
        public void method2(String[] cityList) throws Exception
                  String q="SELECT * FROM table 1 WHERE CITY=?";
                  PreparedStatement ps = con.prepareStatement(q);
                  for (int x=0; x<cityList.length; x++)
                       ps.setString(1, cityList[x]);
                       ResultSet rs = ps.executeQuery();
                           while (rs.next())
                             //code here  
        }Both return the same result but I guess (and correct me if I�m wrong) that it is better to use the prepared statement (efficiency�but how, why?)
    Thanks for any thoughts

    The efficiency issue is not really PreparedStatement versus Statement, but really "bind variables" (which PreparedStatement supports and Satement doesn't) versus not using bind variables, which you can do with PreparedStatement quite easily, thereby throwing away the performance gain (or working around some exceptional cases).
    An extremely detailed analysis of using bind variables, versus not, for Oracle, using Oracle's PL/SQL language, can be found here:
    http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:2444907911913
    For this example, bind variables were 6 times faster for 1,000 test executions...
    The nutshell explanation of this is:
    1) When a database sees a new SQL statement for the first time, it has to figure out how to execute it. This "figuring out" is called "parsing" and is pretty similar to regular code compilation; resources are looked for, references are resolved, and optimizations are applied. It's not cheap. An execution plan results.
    2) Most good databases will cache the SQL and its execution plan, so that if it sees IDENTICAL sql again, it can reuse the execution plan. Bind variables make the SQL identical when the data values change (many DBs use the hashed SQL as a cache key).
    3) Furthermore, as the Oracle example points out, many databases have to lock internal resources while parsing; such locking drastically inhibits parallel execution in mutli-processor environments. Not using bind variables is a great (and all too common) way to turn a $500,000 database installation into the effective equivalent of a $2,000 database.
    Besides the other poster's ease of use issue for quotes and other things, bind variables also help a lot with application security; Google for "SQL injection attack", or see:
    http://www.oracle.com/technology/oramag/oracle/05-jan/o15asktom.html
    Again, this isn't really a JDBC-specific issue.

  • 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.

  • PreparedStatement and empty String instead of space

    Hi all, I would test a space value in a varchar field, i.e.:
    PreparedStatement ps=con.prepareStatement();
    String qry = "select a from table where b=? and c=?";
    ps.setString(1,"value");
    ps.setString(2," "); // space!!
    That source code doesn't work: it set "" (empty String) in the second field, not " " (space).
    Can I use PrepareStatement in any way to do this or I have to use only Statement?
    Thanks.
    Bye.

    my friend, the question was: how do you know the
    parameter is set to "" (empty string)?I don't know: I suppose!!! because it's the only reason for that it returns no record. I tested my query in this three ways:
    1) directly in sqlplus: SELECT OCCFASE As fase, OCLCVVC as convRat, SUM(QTA1) As qta1UM, SUM(QTA2) As qta2UM
    FROM DJITMPRE WHERE OCCFASE IN ('I','P') AND OCCCOSC='XXXXX' AND OCCITEM='RUG-02' AND OCCTPVR = 'RUG'
    AND OCCVAR1 = '01' AND OCCVAR2 = 'WW' AND OCCVAR3 = '12' AND OCCTPIM = '01' AND MAGAZZINO = 'MAG03'
    AND COMMESSA = ' ' AND ORIG = ' ' AND PARTITA = ' ' AND CONFIG = 0.0 AND VANO = ' '
    GROUP BY OCCFASE, OCLCVVC
    and it returns one record.
    2) using Statement:
         Statement s = conn.createStatement();
         String societa=session.getCompanyLogisticName(DSession.TABLE_LOGISTIC);
              StringBuffer qry=new StringBuffer();
              StringBuffer whereClause=new StringBuffer();
              qry.append("SELECT OCCFASE As fase, OCLCVVC as convRat, SUM(QTA1) As qta1UM, SUM(QTA2) As qta2UM ");
              qry.append("FROM DJITMPRE ");
              qry.append("WHERE OCCFASE IN ('I','P') ");
              qry.append("AND OCCCOSC='");
              qry.append(societa);
              qry.append("' ");     
              whereClause.append("AND OCCITEM='");
              whereClause.append(b.getItemCode());
              whereClause.append("' ");
              whereClause.append("AND OCCTPVR = '");
         if (b.getVariantType().equals("")){
              whereClause.append(EscapeString.getLengthString(b.getVariantType(), 1));
         }else{
              whereClause.append(b.getVariantType());
         whereClause.append("' ");
         whereClause.append("AND OCCVAR1 = '");
         if (b.getFirstVariant().equals("")){
              whereClause.append(EscapeString.getLengthString(b.getFirstVariant(), 1));
         }else{
              whereClause.append(b.getFirstVariant());
         whereClause.append("' ");
         whereClause.append("AND OCCVAR2 = '");
         if (b.getSecondVariant().equals("")){
              whereClause.append(EscapeString.getLengthString(b.getSecondVariant(), 1));
         }else{
              whereClause.append(b.getSecondVariant());
         whereClause.append("' ");
         whereClause.append("AND OCCVAR3 = '");
         if (b.getThirdVariant().equals("")){
              whereClause.append(EscapeString.getLengthString(b.getThirdVariant(), 1));
         }else{
              whereClause.append(b.getThirdVariant());
         whereClause.append("' ");
         whereClause.append("AND OCCTPIM = '");
         if (b.getPackingType().equals("")){
              whereClause.append(EscapeString.getLengthString(b.getPackingType(), 1));
         }else{
              whereClause.append(b.getPackingType());
         whereClause.append("' ");
         whereClause.append("AND MAGAZZINO = '");
         if (b.getWarehouseCode().equals("")){
              whereClause.append(EscapeString.getLengthString(b.getWarehouseCode(), 1));
         }else{
              whereClause.append(b.getWarehouseCode());
         whereClause.append("' ");
         whereClause.append("AND COMMESSA = '");
         if (b.getProjectItem().equals("")){
              whereClause.append(EscapeString.getLengthString(b.getProjectItem(), 1));
         }else{
              whereClause.append(b.getProjectItem());
         whereClause.append("' ");
         whereClause.append("AND ORIG = '");
         if (b.getSourceLot().equals("")){
              whereClause.append(EscapeString.getLengthString(b.getSourceLot(), 1));
         }else{
              whereClause.append(b.getSourceLot());
         whereClause.append("' ");
         whereClause.append("AND PARTITA = '");
         if (b.getLotNumber().equals("")){
              whereClause.append(EscapeString.getLengthString(b.getLotNumber(), 1));
         }else{
              whereClause.append(b.getLotNumber());
         whereClause.append("' ");
         whereClause.append("AND CONFIG = ");
         whereClause.append(b.getItemConfiguration());
         whereClause.append("AND VANO = '");
         if (b.getLocation().equals("")){
              whereClause.append(EscapeString.getLengthString(b.getLocation(), 1));
         }else{
              whereClause.append(b.getLocation());
         whereClause.append("' ");
         qry.append(whereClause.toString());
         qry.append(" GROUP BY OCCFASE, OCLCVVC");
    ResultSet rs = s.executeQuery(qry.toString());
    and it returns one record.
    3) using PreparedStatement:
    StringBuffer qry=new StringBuffer();
    qry.append("SELECT OCCFASE As fase, OCLCVVC as convRat, SUM(QTA1) As qta1UM, SUM(QTA2) As qta2UM ");
                   qry.append("FROM DJITMPRE WHERE OCCFASE IN ('I','P') ");
                   qry.append("AND OCCCOSC='").append(societa).append("' ");
                   qry.append("AND OCCITEM=? AND OCCTPVR = ? ");
              qry.append("AND OCCVAR1 = ? AND OCCVAR2 = ? AND OCCVAR3 = ? ");
              qry.append("AND OCCTPIM = ? AND MAGAZZINO = ? AND COMMESSA = ? ");
              qry.append("AND ORIG = ? AND PARTITA = ? AND CONFIG = ? ");
              qry.append("AND VANO = ? ");
              qry.append("GROUP BY OCCFASE, OCLCVVC");
    PreparedStatement bookedQtyPS = conn.prepareStatement(qry.toString());
    bookedQtyPS.setString(1,b.getItemCode());
         if (b.getVariantType().equals("")){
              bookedQtyPS.setString(2,EscapeString.getLengthString(b.getVariantType(), 1));
         }else{
              bookedQtyPS.setString(2,b.getVariantType());
         if (b.getFirstVariant().equals("")){
              bookedQtyPS.setString(3,EscapeString.getLengthString(b.getFirstVariant(), 1));
         }else{
              bookedQtyPS.setString(3,b.getFirstVariant());
         if (b.getSecondVariant().equals("")){
              bookedQtyPS.setString(4,EscapeString.getLengthString(b.getSecondVariant(), 1));
         }else{
              bookedQtyPS.setString(4,b.getSecondVariant());
         if (b.getThirdVariant().equals("")){
              bookedQtyPS.setString(5,EscapeString.getLengthString(b.getThirdVariant(), 1));
         }else{
              bookedQtyPS.setString(5,b.getThirdVariant());
         if (b.getPackingType().equals("")){
              bookedQtyPS.setString(6,EscapeString.getLengthString(b.getPackingType(), 1));
         }else{
              bookedQtyPS.setString(6,b.getPackingType());
         if (b.getWarehouseCode().equals("")){
              bookedQtyPS.setString(7,EscapeString.getLengthString(b.getWarehouseCode(), 1));
         }else{
              bookedQtyPS.setString(7,b.getWarehouseCode());
    //cat.debug("b.getProjectItem(): "+b.getProjectItem());
         if (b.getProjectItem().equals("")){
              //cat.debug("entro in 1 b.getProjectItem().length: "+b.getProjectItem().length());
              bookedQtyPS.setString(8,EscapeString.getLengthString(b.getProjectItem(), 1));
              //bookedQtyPS.setString(8," ");
         }else{
              //cat.debug("entro in 2 b.getProjectItem().length: "+b.getProjectItem().length());
              bookedQtyPS.setString(8,b.getProjectItem());
         bookedQtyPS.setString(8," ");
    //cat.debug("b.getSourceLot(): "+b.getSourceLot());     
         if (b.getSourceLot().equals("")){
              bookedQtyPS.setString(9,EscapeString.getLengthString(b.getSourceLot(), 1));
         }else{
              bookedQtyPS.setString(9,b.getSourceLot());
         bookedQtyPS.setString(9," ");
    //cat.debug("b.getLotNumber(): "+b.getLotNumber());     
         if (b.getLotNumber().equals("")){
              bookedQtyPS.setString(10,EscapeString.getLengthString(b.getLotNumber(), 1));
         }else{
              bookedQtyPS.setString(10,b.getLotNumber());
         bookedQtyPS.setString(10," ");
    //cat.debug("b.getItemConfiguration(): "+b.getItemConfiguration());
         bookedQtyPS.setString(11,""+b.getItemConfiguration());
    //cat.debug("b.getLocation(): "+b.getLocation());     
         if (b.getLocation().equals("")){
              bookedQtyPS.setString(12,EscapeString.getLengthString(b.getLocation(), 1));
         }else{
              bookedQtyPS.setString(12,b.getLocation());
         bookedQtyPS.setString(12," ");
    ResultSet rs = bookedQtyPS.executeQuery();
    and it returns 0 records.
    I hope I explained it well.

  • Using PreparedStatement.setString() on AS/400 VARGRAPHIC field not working

    Hello,
    I have a database table on an AS/400 that contains a VARGRAPHIC field of length 254. According to all the docs that I've read, I should be able to use PreparedStatement.setString() to set a parameter for that field. However, I never get any rows back when I execute the query. If I run the same query on the AS/400 using strsql, the query runs fine and returns the expected results. Anyone have any ideas?
    Thanks

    The Toolbox driver. In that case you might be better off asking this question in a forum that specializes in that. Go here:
    http://www-124.ibm.com/developerworks/oss/jt400/
    You will find a FAQ section, a mailing list you can subscribe to for discussions such as your question, a bug report page where you may be able to see if your question has already been reported as a bug, and so on.
    I haven't used VARGRAPHICS fields so I have no insight into your problem, except that setting graphics data from a String sounds kind of fishy to me. Good luck.

  • PreparedStatement & MySql not working ! Why ?!!?

    Hello everyone. One question for you : I try to have a SELECT on a table to get a column value. I've used for that a preparedstatement but id didn't worked, I mean it returned nothing. Then I've used a simple statement which worked correctly. My question is why prepared doesn't work while simple statement do ?! Other querys work fine, but this one doesn't. And I simply don't get it... I need this preparedstatement way because I use this query very often.
    I use MySQL Connector/J latest version, Java 1.4. Here's the code for this situation:
    This doesn't work:
    String sql = "SELECT IDUSER FROM SUBSCRIBERS WHERE MSISDN = ? AND SUBSCRIBER_TYPE = 0 AND RIGHTS <> 1 LIMIT 1";
    PreparedStatement pstm = null;
    ResultSet rs = null;
    pstm = serviceConnection.prepareStatement(sql);
    pstm.setString(1, MSISDN);
    rs = pstm.executeQuery();
    //gets the iduser from the query
    if (rs.next())
    iduser = rs.getInt("IDUSER");
    else
    iduser = 0;
    This works:
    String sql = "SELECT IDUSER FROM SUBSCRIBERS WHERE MSISDN = "+MSISDN+" AND SUBSCRIBER_TYPE = 0 AND RIGHTS <> 1 LIMIT 1";
    Statement stm = null;
    ResultSet rs = null;
    stm = serviceConnection.createStatement();
    rs = stm.executeQuery(sql);
    //gets the iduser from the query
    if (rs.next())
    iduser = rs.getInt("IDUSER");
    else
    iduser = 0;
    Thank's in advance.

    MSISDN is a String or is a number?
    The non PreparedStatement code works if the sql has
    quotes arrounf this field?
    String sql = "SELECT IDUSER FROM SUBSCRIBERS WHERE
    MSISDN =' "+MSISDN+"' AND SUBSCRIBER_TYPE = 0 AND
    RIGHTS <> 1 LIMIT 1";
    This is something simmilar to the use of
    PreparedStatement.setString();
    The setters of prepared statements are not a simple
    substitution in the sql string. Your database probably
    are thinking that there aren't any row with "not a
    number" in the MSISDN column.The MSISDN is a String representation of a number. And it works with/without the ' around for statements. What's strange is that if I change the prepared statement to be like this:
    String sql = "SELECT IDUSER FROM SUBSCRIBERS WHERE MSISDN = "+MSISDN+" AND SUBSCRIBER_TYPE = 0 AND RIGHTS <> 1 LIMIT 1",
    and I don't use the setString() method it still doesn't work :((

  • Datasources connection questions

    hi all
    my question is about How the connections stored in a Jndi server datasource pool are managed.
    For example, I'm developing a J2EE application with Ejbs and Datasources, etc. I saw that when I want to retrieve a connection from datasource to work on it I need do something like this:
    For example to retrieve a datasource connection:
    Hashtable jndiProps = new Hashtable();
    jndiProps.put(Context.INITIAL_CONTEXT_FACTORY,...);
    jndiProps.put(Context.PROVIDER_URL, ...);
    Context context = new InitialContext(jndiProps);
    DataSource ds = (DataSource) context.lookup("jdbc/MyDatasource");
    Connection con = ds.getConnection();
    ...I know in this case that the server manages a datasource connection pool, etc
    My question is when a get a connection from the Datasource pool of my app server. do I need to release the connection with some special method when I finish with it (in order to return it to the pool) or it doesn't matter ?
    thanks in advance

    If I have three prepared statements right in a row with nothing in between should I close the connection after each one and then get it again?
    Seems like I would be just as well off to just get the conn once do the 3 things then close it.
    and in spots I might actually be doing something as i step through the first result set so can i use conn.preparedStatement() in the loop many times without getting the connection and closing each time through the loop?
    i of course close all PS and RS and use diff PS2 and RS2 in the loop so i 'm just talking about keeping the conn open while (RS.next()) and use it multiple times to conn.preparedStatement() inside the loop?
    or should i use 2 connections lol and open conn1 and then in loop use conn2 and close it each time around the loop and then close conn1 when i exit the loop?

  • Beginner question about prepared statements...PLEASE help! :-)

    First let me say thanks for the assistance. This is probably really easy to do, but I'm new to JSP and can't seem to figure it out.
    I want to dynamically populate a table that shows whether a particular person has an appointment at a given date and time with a user. To do this, I want to query the MySQL database for the lastname of the person with the appointment that occurs with the user at the year, month, date, and time, in question.
    THE CODE BELOW DOESN'T WORK (obviously) BUT SOMEWHAT ILLUSTRATES WHAT I'M TRYING TO ACCOMPLISH:
    <%
    Driver DriverTestRecordSet = (Driver)Class.forName(MM_website_DRIVER).newInstance();
    Connection ConnTestRecordSet = DriverManager.getConnection(MM_website_STRING,MM_website_USERNAME,MM_website_PASSWORD);
    PreparedStatement StatementTestRecordSet = ConnTestRecordSet.prepareStatement("SELECT lastname FROM appts_pid1 WHERE user_id='<%=(((Recordset1_data = Recordset1.getObject(user_id))==null || Recordset1.wasNull())?"":Recordset1_data)%>' AND year='<%= yy %>' AND month='<%= months[mm] %>' AND date='<%= dates[dd] %>' AND appttime='16:15:00'");
    ResultSet TestRecordSet = StatementTestRecordSet.executeQuery();
    boolean TestRecordSet_isEmpty = !TestRecordSet.next();
    boolean TestRecordSet_hasData = !TestRecordSet_isEmpty;
    Object TestRecordSet_data;
    int TestRecordSet_numRows = 0;
    %>
    The real problem comes in the prepared statement portion. If I build the prepared statement with static values like below, EVERYTHING WORKS GREAT:
    PreparedStatement StatementTestRecordSet = ConnTestRecordSet.prepareStatement("SELECT lastname FROM appts_pid1 WHERE user_id='1' AND year='2002' AND month='October' AND date='31' AND appttime='16:15:00'");
    But when I try to use dynamic values, everything falls apart. It's not that the values aren't defined, I use the user_id, year <%= yy %>, month <%= months[mm] %>, etc. elsewhere on the page with no problems. It's just that I can't figure out how to use these dynamic values within the prepared statement.
    Thanks for reading this far and thanks in advance for the help!!!!

    Hi PhineasGage
    You are little bit wrong in your
    your preparedStatement.
    Expression tag within scriptlet tag is invalid.
    Whenever you are appending the statement with
    expression tag, append it with "+" and remove
    expression tag.
    Hopefully it will work
    ThanksThanks for the response!
    I know that the expression tag within scriptlet tag is invalid. I just need a workaround for what I want to do.
    I'm unclear what you mean by "Whenever you are appending the statement with expression tag, append it with a "+" and remove expression tag".
    Could you give an example?
    In the meantime, I've been trying to digest the docs on prepared statements and have changed the code to look like:
    PreparedStatement StatementTestRecordSet = ConnTestRecordSet.prepareStatement("SELECT lastname FROM appts_pid1 WHERE user_id= ? AND year= ? AND month= ? AND date= ? AND appttime='13:15:00'");
    StatementTestRecordSet.setInt(1,1);
    StatementTestRecordSet.setInt(2,2002);
    StatementTestRecordSet.setString(3,"October");
    StatementTestRecordSet.setInt(4,31);
    Again, WITH THE STATIC VALUES, THIS WORKS FINE...but when I try to use expressions or variables like below, things don't work:
    StatementTestRecordSet.setInt(2,<%= yy %>);
    Obviously, I'm doing something wrong, but there has to be a way to use variables within the prepared statement.
    ALSO, the values are being passed to this page via URL in the form:
    samplepage?user_id=1&year=2002&month=October&date=31
    Based upon this information, is there another way (outside of stored procedures in the db) to do what I want to do? I'm open to ideas.

  • A question about compatiblilty of JDBC

    Hi, there,
    I have a question about JDBC 3.0 in JDK1.4.1.
    We build a .jar using JDK1.4.1 and this .jar file
    provides JDBC 3.0 interface.
    I then tried to call the interface under JDK1.3.1
    but it keeps asking me about the getParameterMetaData()
    in PreparedStatement.
    (The error message like this:
    Exception in thread "main" java.lang.NoClassDefFoundError: java/sql/ParameterMetaData dbmaker.sql.JdbcOdbcConnection.prepareStatement(JdbcOdbcConnection.java:257)
    I did implement the getParameterMetaData() method,
    but I didn't call this method in my testing program.
    It's quite strange since when JDK1.2 was release,
    we implemented the getBlob() method in
    ResultSet class and there's no problem when we
    use JDK1.1 run time to call this ResultSet object.
    Could any one tell me why? Is this caused by a
    compatibility problem between JDK1.4 and the
    older versions of JDK?

    Hi, there,
    Let me outline the condition by examples so that maybe you can help me. PLEASE! Could somebody tell us what's wrong?
    - CASE 1:
    In JDK1.2, we implemented a new method getBlob which returns the type of Blob (this is done according to JDBC 2.0 specification.) in ResultSet class. We can use the .jar compiled by jdk1.2 in jdk1.1 environment.
    e.g. We make a xyz.jar by jdk1.2 and the xyz.jar includes new method getBlob in ReaultSet class. Then, one java application including ResultSet class CAN run under jdk1.1 with xyz.jar, if the method ResultSet.getBlob() is not called.
    - CASE 2:
    BUT, the following case which is the same as in the above condition will fail in jdk1.3 environment.
    In JDK 1.4, we implemented a new method getParameterMetaData() which returns the type of ParameterMetaData. (BTW, this is done according to JDBC 3.0 specification.) in PreparedStatement class. We CANNOT use the .jar compiled by jdk1.4 in jdk1.3 environment.
    e.g. We make a ttt.jar by jdk1.4 and ttt.jar includes the new method getParameterMetaData() in PreparedStatement class. Then, one java application including PreparedStatement class CANNOT be run under jdk1.3 with ttt.jar, even when the method PreparedStatement.getParameterMetaData() is not called.

  • How to get input  string with resolved '?' of PreparedStatement?

    Is there a way to retrieve the input string of a PreparedStatement?
    Example:
    ps = connection.prepareStatement("update t1 set name=?");
    ps.setString(1, "test");Now, can I get the input string "update t1 set name=?" back from the PreparedStatement object with the '?' resolved? In this case:
    update t1 set name='test'
    ?

    Sir,
    Thank you first for responding. I appreciate your time in dicussing things here. Just saying.
    I see that you suggested and that is sort of agood
    tool for this but I think I would want to do more
    testing with the actual driver no?
    Not sure what you mean by "testing with the actual
    driver". The suggestion that I made is a proxy, not
    a substitute.
    Right. Never mind. I got myself confused.
    Actually I would like to ask a serious question
    here... can you give an example of why you don'tknow
    what the SQL will look like? I'm just trying to
    understand why you don't know and I'm strugglingwith
    that.1. Dynamic creation of SQLUgh. Okay. But still ugh.
    2. Unknown input of parameters.I still don't understand why they would be unknown if it is your app inputting them.
    Sincerely,
    Slappy

Maybe you are looking for

  • Please Help ME make a 3D Logo And Fevicon

    Hello everyone, I have brought a website Trendybuzz.in. and for it i want 3D logo and Fevicon. I have tried my self for so many times but still i am not able to make 3D logo, so please help make a logo and fevicon. Also i want logo in different forma

  • Multiple SQL_HANDLE_DBC handles do not work on Linux

    Hello, I am seeing the following error from the SQL Server Driver For Linux when I attempt to execute a query on a SECOND connection within my application: SQLSTATE: IM001 Native Error Code: 0 Message: [unixODBC][Driver Manager]Driver does not suppor

  • Embed links in video

    I would like to embed links to other website locations within the video.  If this is possible, how can I do it? The scenario is that when a person is watching a particular video, links would appear on the screen that would take them to more specific

  • Lotus Notes Applications

    All, Does anyone have any experience of migrating a Lotus Notes application to HTML DB ? Are there any tools available/proposed/in development to allow this ? Any help would be appreciated even if it is a no Thanks in advance Chris

  • Trouble sharing mac internet to linux server over ethernet

    Hi. I turned on internet sharing over ethernet to my linux server which is a dell poweredge. I went into network and at first it had a self assigned IP. Then I manually changed it to the correct subnet and the same IP address as my mac. Since I know