PreparedStatement and batchExecute

Hi,
I am trying to use PreparedStatement and batchExecution for inserting a few rows into database. I am using JTurbo driver.
But it only inserts the last set of values. For Example
Class.forName( "com.ashna.jturbo.driver.Driver" );
Connection con = DriverManager.getConnection( "jdbc:JTurbo://server","username","password" );
PreparedStatement pstm = con.prepareStatement( "INSERT INTO Test( ids, age, wt ) VALUES(?,?,?)" );
int ids[] = {1000,1001,1002,1003};
String[] age = { "12","13","14","15" };
String[] wt = { "45","46","47","48" };
for( int i=0 ; i<ids.length ; i++ )
pstm.setInt( 1, ids[i] );     
pstm.setString( 2, age[i] );
pstm.setString( 3, wt[i] );     
pstm.addBatch();
int[] rows = pstm.executeBatch();
pstm.clearBatch();
con.close();
In database, it shows
1003, 15, 48
1003, 15, 48
1003, 15, 48
1003, 15, 48
Pls..pls..help me with this...i'm having a hard time figuring out this problem.. :(
Thanks a lot...

Maybe you just wrote this short-hand but if not try this:
pstm.setInt( 1, ids[i] );
pstm.setString( 2, age[i] );
pstm.setString( 3, wt[i] );
//...........

Similar Messages

  • What's the difference between "PreparedStatement" and "Statement"?

    What's the difference between "PreparedStatement" and "Statement"?
    Which is better??????

    Read the docs for the two classes. The differences are apparent there.
    Which one is better depends on your needs. I think that constructing and executing a PreparedStatement can be a bit less performant than just a Statement, if you're only executing the query one time. But I don't think that difference will normally be noticable in the context of a given application.
    Additionally, if you have to pass any dates or strings to the query, you'll want PreparedStatement's parameters, rather than trying to format and escape things in the query string.

  • Using PreparedStatement and the Oracle Error ORA-1000

    Hi,
    I have a question about PreparedStatement objects that is not so simple to explain for me. What I would like to know is: if I use a PreparedStatement following traditional and generic steps:
    1- PreparedStatement pStmt = Connection.prepareStatement(sQuery);
    2- pStmt.setXXX(i,j);
    n - pStmt.setXXX(i,j);
    n+1 - ResultSet rs = pStmt.executeQuery();
    n+2 - while(rs.next()){ ... retrive ResultSet data  ... }
    n+3 - rs.close()
    n+4 - back to point number 2
    and at the end (as you can see in the point numbered n+4), instead of closing the PreparedStatement pStmt using the close() method, I reuse the PreparedStatement pStmt comeing back to the point numebr 2 and setting again all its parameters with new values ... then ... what heppens in the Oracle database ? Has been the cursor (so the mamory area), associated to my PreparedStatement object pStmt, duplicated or is it the same ?
    I know that Java allows you to do this kind of operations with PreparedStatement, and I know that in tha Java Documentation is explained to follow this strategy to optimize the execution time because in this way the same PreparedStatement is precompiled and prepared only once. But if I do a for loop following the steps explained before, after many iterations I have the error "ORA-1000: maximum open cursors exceeded". This error is the reason of my question. Does this error means that it's mandatory to close a PreparedStatement always, otherwise if you reuse it without closing it then the corresponding database cursor will be duplicated ? If it is so, then I think this is a contradiction with official java documentation ...
    I'm using Oracle8i (version 8.1.7) and Oracle JDBC Thin Driver (Windows NT) for use with JDK 1.2.x. Moreover, in my database istance the parameter "maximum open cursor" is equal to 800 ...
    Thank you very much for suggestions :-)

    There is no need to close a prepared statement or its resultset for every iteration.
    After the first iteration in a loop, all subsequent executions of it will close the previous resultset. By adding close() method, you are making one extra costly call to the DB for no reason.
    Following is the sample code.I know what you are saying. In fact at the beginning I wrote my code in the same way of your sample (see the code of my first post at the begin of this page).
    But doing so, after thousand iterations of the loop, I had "Oracle Error ORA-1000 : maximun open cursor exeeded" even if in my database istance the parameter "maximum open cursor" is equal to 8000.
    At this moment in my code, for each iteration, I close the PreparedStatement and in this way I don't have anymore the error :-((
    So it seems that only in theory we can reuse a preparedStatement without closing it. In fact if we see the oracle system table "$open_cursor" (as Konrad Pietzka suggest me) we can find that, for each interation,
    at our line code "rs = pstmt.executeQuery();" correspond a new cursor in the database: this means that for each method "pstmt.executeQuery()" the database open a new cursor and do not use the previous one as it should.
    I posted a question two months ago to search if someone had the same problem (it seems that Konrad Pietzka had the same situation) and was able to explain me what is the cause.
    The only reason I found by myself for this problem, is that probably the Oracle JDBC Thin Driver for Windows NT/2000 has some bugs... but I'm not sure ...
    Thank you very much for you time !!
    bye :-))
    Fidalma

  • PreparedStatement and "in" clause

    I am trying to pass an "in" clause to a SQL statement as a bind variable, but keep getting an "invalid number" runtime error:
    The "where" clause of the SQL statement is:
    String wherestmnt = "where sh.header_id in ? ";
    I am using a PreparedStatement and am setting the bind variable as follows:
    pstmt.setString(1,"(34552)")
    If I change the "in" clause to "=" and do a set as pstmt.setString(1,"34552") it works fine.
    Any advice?
    null

    There is also another error. If you need to use the in clause the values must be within paranthesis,
    So if your query were like,
    select * from emp where empno in (?)
    then the bind would work. You can have as many ? as you want separated by commas and you can bind that many values..!

  • PreparedStatement and bind variable

    We are experiencing some werid performance break downs where database server looks healthy and our java applications are down to their knees.
    I was wondering if someone could help me clarify the comparison between PreparedStatement and bind variable. When I execute a PreparedStatement in java through the JDBC thin driver, would the database consider it a dynamic SQL or is it a SQL using bind variable? If this same statement is executed 100000 times, is it parsed 100000 times? We are using JDK131. How does it work?
    Is there any memory leak in PreparedStatement implementation in JDBC thin driver? Is there any known symptom to this problem? What is the recommended solution?
    Thank you very much!

    If PreparedStatement is parsed and cached, why is there setting to set implicit statement caching and explicit statement caching? Our DBA insists that it is parsed every single time. How would I find out for sure?
    The SQLs have not been changed. This sudden performance degradation started when a new client went live and we experienced higher than usual volumn. We are connecting using JDBC thin client from weblogic server to Oracle 8.1.7. It's been happening everyday since the client went live and the only way to get the performance back is to shutdown and restart the database server.
    I tried to search JDBC related issues. The only complain that I've found so far is that there may be some potential memory leak for a PreparedStatement. However, I have not found anything from Oracle's website that concurs to that.
    What is my best bet?

  • Database Procedure Calling by Using PreparedStatement and CallableStatement

    Hi
    We can execute Database Stored Procedure by using PreparedStatement and CallableStatement as well.Then what is the significance of having CallableStatement.
    Please let me know the difference between these two Statement objects particularly in Stored Procedures Execution.
    Thanks in advance
    Basha007

    A callable statement excecutes a stored procedure that's stored and run on the database server.
    A prepared statement doesn't require a database stored procedure. It's parsed and cached by the JDBC driver, and allows you to specify parameters and bind values to them at runtime. Those are usually used in loop constructs where you want to repeatedly execute the same SQL with different values.
    Not all RDBMS support stored procedures (e.g., MySQL), but every driver I've used allows PreparedStatements. - MOD

  • To Joe Schell - jschell... - PreparedStatement and executeBatch()

    Hi,
    Thanks for the reply to the PreparedStatement and executeBatch() query. Is there any workaround for it other than using the Statement object?
    thanks,
    Nish

    Could be.
    But since I have no idea about what you are talking about, I can't really comment.
    I respond to between 10-30 threads a day and read more than that. Consequently I need a context to understand questions.
    If I have previously (recently) responded to a previous thread then if you post a response to it I will generally see it in less than a day. If is an older thread you might want to start a new thread. But if you do then add a link or put enough content so I can follow it.

  • Suggestion regarding running preparedstatement and batchupdate

    I have to insert many rows in database therefore i use preparedstatement and for loop.I want to know if i add all the query in batch and then execute will it give better performance .Will sql statement is still in compiled form when execute in batch .Let if i add another sql statement which is different from previous sql statement in batch what the effect it has on performance.
    Thanks

    hi.,
    check this out..
    http://forum.java.sun.com/thread.jspa?threadID=154870&start=15&tstart=0

  • PreparedStatements and LIKE clauses

    Hi,
    I've come across a slight problem with PreparedStatements and LIKE clauses. Say I want my query to look something like this:
    SELECT * FROM CONTENT_TABLE WHERE CONTENT LIKE '%test%'If I were to use a PreparedStatement I'd do something like this:
    PreparedStatement searchContent = con.prepareStatement("SELECT * FROM CONTENT_TABLE WHERE CONTENT LIKE ?");
    searchContent.setString(1, queryString);This isn't correct becuase it matches where CONTENT LIKE 'queryString'
    I tried this:
    PreparedStatement searchContent = con.prepareStatement("SELECT * FROM CONTENT_TABLE WHERE CONTENT LIKE '%?%'");
    searchContent.setString(1, queryString);But I get a syntax error in my SQL.
    Is there another way around this?
    Thanks

    just guessing try this:
    PreparedStatement searchContent = con.prepareStatement("SELECT * FROM CONTENT_TABLE WHERE CONTENT LIKE '%?%'");searchContent.setString(1, "%"+queryString+"%");
    This might work, since ? gets replaced by '...', so i am guessing %..% will fit..
    give it a shot, i might be wrong.

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

  • PreparedStatement and open cursors

    Hi,
    i write an application where it is necessary to get a lot of preparedStatements in one connection. The preparedStatements are used
    only once and they are closed after the usage. But it seems to me that this close
    has no effect. Depending on the value in open cursors the error ORA - 01000 raises and it is not possible to get another preparedStatement without closing and opening the connection. But that increases the runtime to much and the application is a performance-critical application.
    Does anyone have an idea how to solve the problem?
    Thanks

    >
    Any thoughts what could be the problem. Only time I ever got them was because the result set, statement, connection wasn't being closed or wasn't being closed in the correct order.

  • 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! :)

  • PreparedStatements and MySQL Connector/J

    Hi All,
    I was wondering what is the exact SQL statement that is passed to MySQL server when we use PreparedStatements. I was trying using MySQL Connector/J, type4 driver. I tried with a simple servlet
        public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException   {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<html>");
            out.println("<body>");
            out.println("<head>");
              try {
                   Class.forName("com.mysql.jdbc.Driver");
                   Connection con=DriverManager.getConnection("jdbc:mysql://localhost/mydb?user=root","root","");
                   //Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                   //Connection con=DriverManager.getConnection("jdbc:odbc:test");
                   PreparedStatement pst=con.prepareStatement("select * from AS_ITM where ID_ITM=?");
                   out.println("PreparedStatement = "+pst);
                   out.println("<br>");
                   pst.setString(1, "10");
                   out.println("PreparedStatement = "+pst);
                   //ResultSet rs=pst.executeQuery();
                   con.close();
              }catch(Exception e){
                   out.println(e);
            out.println("</head>");
            out.println("<body>");
            out.println("</body>");
            out.println("</html>");
    Here I am printing PreparedStatement  object's generated SQL twice and not even executing the query.
    And the result is:
    PreparedStatement = com.mysql.jdbc.PreparedStatement@19f3736: select * from AS_ITM where ID_ITM=** NOT SPECIFIED **
    PreparedStatement = com.mysql.jdbc.PreparedStatement@19f3736: select * from AS_ITM where ID_ITM='10'
    See second statement? I have not even sent it to the server.
    So is this jdbc driver preparing a simple Statement before it is sent to MySQL server?
    Is it what a jdbc driver is supposed to do? So then whats the use of PreparedStatement?Thanks,
    Kishor

    Hi,
    Just exactly what a JDBC driver is supposed to do with a PreparedStatement is not specified in JDBC I believe. I think they only requirement is that a PreparedStatement should be able to insert the various data types correctly into an SQL string.
    I am fully aware that PreparedStatements should also be able to give a better performance, for instance by only sending the parameters when you use it the second time, and not the whole the SQL. But I think this is up to the database and driver implementation to decide whether to do this, and how.
    Remember, the JDBC driver may be sending other information across to the database than the SQL. We can't see that from looking at the PreparedStatement only. You would have to use a network packet sniffer to see all data exchanged between the driver and the database
    -Jakob Jenkov

  • Problems with PreparedStatement and MySQL selecting bytes

    Hi,
    i have a problem trying to select information when the "select" has a byte restrict.
    The table in database is:
    CREATE TABLE `positions` (
    `PKID` int(10) unsigned NOT NULL auto_increment,
    `POSCODE` varbinary(30) NOT NULL,
    `ISWTURN` binary(1) NOT NULL,
    `QTT_GAMES` int(10) unsigned NOT NULL default '1',
    PRIMARY KEY (`PKID`),
    UNIQUE KEY `UNIQ_POS` (`POSCODE`,`ISWTURN`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    And the test code to get the qtt_games is :
    conn = DriverManager.getConnection (url,user,pwd);
    byte bcode[] = poscode.getByteArrayCode();
    // bcode is inserted ok in another preparedstatement...
    String query = "SELECT qtt_games FROM positions "+
         "WHERE poscode=? and iswturn=?";
    PreparedStatement pstmt = conn.prepareStatement(query);
    pstmt.setBytes (1,bcode);
    pstmt.setByte (2,poscode.getIsWhiteTurn()); //it returns a byte
    ResultSet rs = pstmt.executeQuery (query);
    When pstmt.executeQuery is reached, it's thrown the exception:
    com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '=? and iswturn=?' at line 1
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2870)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1573)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1665)
    at com.mysql.jdbc.Connection.execSQL(Connection.java:3170)
    at com.mysql.jdbc.Connection.execSQL(Connection.java:3099)
    at com.mysql.jdbc.Statement.execute(Statement.java:695)
    at app.server.bbdd.MYSQLBDManager.getGamesBasicInfo(MYSQLBDManager.java:942)
    at app.server.bbdd.MYSQLBDManager.main(MYSQLBDManager.java:1068)
    Can anybody tell me what's wrong?? I think the query is ok, but don't know what's happening with this...
    Lots of thanks.

    Don't cross-post, it's considered rude:
    http://forum.java.sun.com/thread.jspa?threadID=5122604&messageID=9430056#9430056
    http://forum.java.sun.com/thread.jspa?threadID=5122603&messageID=9430050#9430050
    One to a customer, please.
    %

  • PreparedStatement and 'Order by'

    How can a PreparedStatement be made in this situation?
    String query = " Select * from myTable where id=? Order by ? ? ";
    PreparedStatement  ps = con.prepareStatement( query);
    ps.setInt(1,userID);
    ps.setString (2, columnName );
    ps.setString (3, ascOrDesc );The problem is the 3rd value. You cannot stick 2 question marks together like that. However, if I do the following it compiles, but the query doesn't place the values in order.
    String query = " Select * from myTable where id=? Order by ?  "+ascOrDesc;
    PreparedStatement  ps = con.prepareStatement( query);
    ps.setInt(1,userID);
    ps.setString (2, columnName );So, what to do?

    Just to make the answer more clear, you cannot use the same prepared statements for ascending and descending sorts. You need one for each.
    String query = " Select * from myTable where id=?
    Order by ? asc ";
    PreparedStatement  ps = con.prepareStatement(  query );
    ps.setInt(1,userID);
    ps.setString (2, columnName );Of course, you can refactor this into a single method, something like:
    static final String MYTABLE_QUERY = "Select * from myTable where id=? Order by ?";
    public String getMyTableQuerySQL( boolean isAscending )
         return MYTABLE_QUERY + ( isAscending ? " asc" : " desc" );
    PreparedStatement st = con.prepareStatement( getMyTableQuerySQL( isAscending ) );Another cool thing to do (that belongs in another thread) is to wrap Connection in an envelope that implements the Connection interface and add a PreparedStatement cache. This optimally will be a PooledConnection. Here's a niave skeletal implementation:
    First we'll write the statement cache we will be using. This is an LRU map using STATEMENT_CACHE_SIZE to set the max number of elements we want in the cache. I usually make this settable by a property with a default of 8.
        class StatementCache extends LinkedHashMap
            public StatementCache()
                super( STATEMENT_CACHE_SIZE, 0.75f, true );
            protected boolean removeEldestEntry( final Map.Entry eldest )
                if ( size() <= STATEMENT_CACHE_SIZE )
                    return false;
                else
                    final CachedPreparedStatement ps =
                        (CachedPreparedStatement)eldest.getValue();
                    if ( ps.isActive() )
                        return false;
                    try
                        ps.reallyClose(); // NOTE: Really close the statement
                    catch ( SQLException e )
                        e.printStackTrace();
                    return true;
        }Now we need to wrap PreparedStatement:
    class CachedPreparedStatement implements PreparedStatement
        /** The real statement we are delegating to */
        private PreparedStatement m_statement;
        /** We change the behavior of close to just flip this switch. */
        protected boolean m_active = true;
        public CachedPreparedStatement( final String sql, final Connection con ) throws SQLException
            m_statement = con.prepareStatement( sql );
        public boolean isActive()
            return m_active;
        public boolean setActive( boolean isActive )
            m_active = isActive;
        public void close() throws SQLException
            clearParameters();
            try
                clearWarnings();
            catch ( SQLException e )
                e.printStackTrace();
            // mark it as no longer active
            setActive( false );
        public void reallyClose() throws SQLException
            setActive( false );
            m_statement.close();
        // now just delegate all the rest of the interface methods to m_statement
    }Finally, we wrap Connection:
    class PooledConnection extends implements Connection
        /** A map of cached statements */
        private Map m_statementCache = new StatementCache();
        /** The connection we are delegating to */
        private Connection m_connection;
        /** {@inheritDoc} */
        public PreparedStatement prepareStatement( final String sql )
            throws SQLException
            // create or fetch a cached prepared statement and activate
            final CachedPreparedStatement statement = (CachedPreparedStatement)
                m_statementCache.get( sql );
            if ( statement != null )
                statement.setActive( true );
                return statement;
            else
                // need to create a new one and cache it
                final CachedPreparedStatement ps =
                    new CachedPreparedStatement( sql, m_connection );
                m_statementCache.put( sql, ps );
                return ps;
        // now just delegate the rest of the interface methods to m_connection
    }The Connection class provided by your JDBC driver should close all open statements when the connection is closed. However, if you are not sure about this, you can implement #close on your Connection class to first iterate throught the cache and close each statement.

Maybe you are looking for

  • IPhone won't show up in itunes but does show up in iphoto (?)

    So my iphone won't show up in itunes, but is recognized by iphoto. I did recently sync the music on the phone with another itunes on a windows pc because I was getting on a flight and wanted to hear the show that I had just seen and downloaded. Could

  • SUGGESTION FOR APPLE, APPLE PLEASE READ THIS!!!

    Okay ive been thinking and i believe apple can do some upgrades to the trackpad in a software update to do even more amazing stuff for example: -how about you touch the four corners of your trackpad to turn off your laptop -or three corners for resta

  • How to change selected pane's color in a JTabbedPane ?

    Hi there ! I'm tryin' to change selected pane's color (default : light gray) in a JTabbedPane. I tried to use the following code : UIManager.put("TabbedPane.selected", new Color(255,255,200)); but it doesn't seem to work. Any idea ? Thanks.

  • Purchase order generating multiple outputs

    Hi All, We are facing this unusal problem where the PO is generating multiple messages .The most tricky part is its doing only in the morning at 9.30 am when the goods movement file is run. During this time the PO close goes crazy and it generates mu

  • Need some ideas for programmatic/dynamic ADF BC using JDeveloper 10.1.3

    Using ADF Faces 10g, I built a page which is used to upload an excel file to the server. The contents of the spreadsheet is further parsed into a 2 dimensional array. In addition, I am able to determine the database table information from the workshe