Error 01006 with prepared statement

I have the 1006 error with the statement:
prepstmt = conn.prepareStatement
select col from table where col = '?'
The parameter is set with setString().
I tried with the oracle 815 and 817 drivers.

where i've to put STATEMENT.RETURN_GENERATED_KEYS?
I need to use executeUpdate()...I didn't put it anywhere. I just called the getGeneratedKeys() method without using that constant anywhere and it just worked.

Similar Messages

  • Autogenerated key with Prepared Statement...

    Hi guys,
    i've a question and i need help...
    how can i retrieve autogenerated key with prepared Statement?
    I see examples only about statements...please post me example code..

    where i've to put STATEMENT.RETURN_GENERATED_KEYS?
    I need to use executeUpdate()...I didn't put it anywhere. I just called the getGeneratedKeys() method without using that constant anywhere and it just worked.

  • Update record with prepared statement

    Below is my prepared statement that I cannot get to work, I keep getting a stack trace error that I cannot understand.
    //methodClass.class
    public void updateUser(String pwd,String userid,Timestamp pwdtime)
            String updateStatement = "update userSec set password=(?), passwordChanged=(?) where userId =(?)";
                try
                    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                    objConn = java.sql.DriverManager.getConnection("jdbc:odbc:sensorWeek","","");
                    PreparedStatement ps = objConn.prepareStatement(updateStatement);
                    ps.setString(1, pwd);
                    ps.setString(2, "YES");
                    ps.setString(3, userid);
                    ps.setTimestamp(4,pwdtime);
                    ps.executeUpdate();
                    ps.close();
                    objConn.close();
                catch (SQLException s)
                    System.err.println("SQL Error in updateUser Prepared Statement");
                    s.printStackTrace();
                catch (Exception e)
                    System.err.println("Error in updateUser Prepared Statement");
                    e.printStackTrace();
      }I call the ps from the jsp like so:
    java.util.Date currentDate = new java.util.Date();
    java.sql.Timestamp ts = new java.sql.Timestamp(currentDate.getTime());
    methodClass mc = new methodClass();
    mc.updateUser(request.getParameter("pwd3").toString(),request.getParameter("userId").toString(),ts);Here is the stack trace:
    type Exception report
    message
    description The server encountered an internal error () that prevented it from fulfilling this request.
    exception
    org.apache.jasper.JasperException: sensorPac.methodClass.updateUser(Ljava/lang/String;Ljava/lang/String;Ljava/sql/Timestamp;)V
         at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:254)
         at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:295)
         at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:684)
         at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:432)
         at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:356)
         at org.apache.jasper.runtime.PageContextImpl.forward(PageContextImpl.java:430)
         at org.apache.jsp.checkPwd_jsp._jspService(checkPwd_jsp.java:69)
         at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:137)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:210)
         at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:295)
         at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:247)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:193)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:256)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.valves.CertificatesValve.invoke(CertificatesValve.java:246)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardContext.invoke(StandardContext.java:2416)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:180)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.valves.ErrorDispatcherValve.invoke(ErrorDispatcherValve.java:171)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:172)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:174)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.coyote.tomcat4.CoyoteAdapter.service(CoyoteAdapter.java:223)
         at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:601)
         at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:392)
         at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:565)
         at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:619)
         at java.lang.Thread.run(Thread.java:534)
    root cause
    javax.servlet.ServletException: sensorPac.methodClass.updateUser(Ljava/lang/String;Ljava/lang/String;Ljava/sql/Timestamp;)V
         at org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:536)
         at org.apache.jsp.changePwd_jsp._jspService(changePwd_jsp.java:295)
         at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:137)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:210)
         at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:295)
         at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:684)
         at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:432)
         at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:356)
         at org.apache.jasper.runtime.PageContextImpl.forward(PageContextImpl.java:430)
         at org.apache.jsp.checkPwd_jsp._jspService(checkPwd_jsp.java:69)
         at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:137)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:210)
         at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:295)
         at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:247)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:193)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:256)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.valves.CertificatesValve.invoke(CertificatesValve.java:246)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardContext.invoke(StandardContext.java:2416)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:180)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.valves.ErrorDispatcherValve.invoke(ErrorDispatcherValve.java:171)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:172)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:174)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.coyote.tomcat4.CoyoteAdapter.service(CoyoteAdapter.java:223)
         at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:601)
         at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:392)
         at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:565)
         at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:619)
         at java.lang.Thread.run(Thread.java:534)
    Any Ideas?
    Thanks!!

    Sorry, I mistyped the statement, here is the corrected statement:
    public void updateUser(String pwd,String userid,Timestamp pwdtime)
            String updateStatement = "update userSec set password=(?), passwordChanged=(?),passwordChTime = (?)  where userId =(?)";
                try
                    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                    objConn = java.sql.DriverManager.getConnection("jdbc:odbc:sensorWeek","","");
                    PreparedStatement ps = objConn.prepareStatement(updateStatement);
                    ps.setString(1, pwd);
                    ps.setString(2, "YES");
                    ps.setTimestamp(3,pwdtime);
                    ps.setString(4, userid);
                    ps.executeUpdate();
                    ps.close();
                    objConn.close();
                catch (SQLException s)
                    System.err.println("SQL Error in updateUser Prepared Statement");
                    s.printStackTrace();
                catch (Exception e)
                    System.err.println("Error in updateUser Prepared Statement");
                    e.printStackTrace();
      }

  • Problem in Wilcard Search (%) with Prepared Statement

    Hello Everyone,
    Im trying to search using the like operator within a prepared statement. The program compiles , but when I execute it I get an empty result set.
    I tried the same query in Query Analyser in SQL Server 2000 and it worked flawlessly.
    I searched on this forum also and I read recommendations suggesting
    to put the ? in like '?'   This gives me an error.
    Ive tried all options I could get my hands on ,now I request you all to please provide me some guidance.
    Thankyou
    The code snippet is as follows :
              String  sDay= "%"+startDay+"%";
                    ps= con.prepareStatement("Select  *  from Testdb  where days like ? ");
              ps.setString(1,sDay);
              As I said earlier, this query returns and empty result set.
    Thankyou once again.

    Its next to impossible for me to switch to Statement from prepared S. because the Query has got way to many conditions and its next to impossible to handle all those in a statement.
    I had originally started out with statement itself but then I switched to prepared statement as it was getting unmanageable.
    I'll try finding a work around whereby I split the query into two parts using the manageable part and the Wilcard search in the statement and the other unmanageable part in the PS.
    Else I will again have to attempt that. I had also had a feeling this was affecting it.
    Thanks for the help.
    If anyone has some solution please post it .
    Thank you.

  • Problem with Prepared Statement & MS Access

    Hi
    I have tried to find some info about this but can't see anything specific to what I think the problem may be. Hopefully someone can point me in the right direction.I am trying to get information out of an MS Access database using a Prepared Statement but I am getting strange results.
    When I run the query in the database it gives me the correct totals (�51) for 4 records. When I run the Prepared Statement ,I get 81. Has it got anything to do with the data type I am using( sorry if this is a really basic question). here is my code- the connection etc is elsewhere.
    private void getReportMoneyTotal() throws SQLException
              Calendar todayTotal =Calendar.getInstance() ;
               SimpleDateFormat reportDateFormat = new SimpleDateFormat("dd MM yyyy");
              PreparedStatement preparedT =context.getConnection().prepareStatement(
                   "SELECT Sum(tblSession.Fee) AS Total, Count(tblBooking.BookingID) AS CountOfBookingID FROM tblSession INNER JOIN "+
                   "(tblBooking INNER JOIN tblCustomer_Booking ON tblBooking.BookingID = tblCustomer_Booking.BookingID) ON tblSession.SessionID = tblBooking.SessionID "+
                   "WHERE (((tblBooking.EventDate)>DateAdd('m',-1,#"+reportDateFormat.format(todayTotal.getTime())+"#)) AND ((tblSession.Session)='Morning' Or (tblSession.Session)='Evening')) OR (((tblSession.Session)='Afternoon') AND ((tblBooking.Extension)=Yes))"
              ResultSet resultTotal =preparedT.executeQuery();
              resultTotal.next();
              Double total =resultTotal.getDouble("Total");
              Locale locale = new Locale("GBP");
            NumberFormat gbpFormat = NumberFormat.getCurrencyInstance(locale);
              System.out.println(gbpFormat.format(total));
              preparedT.close();
         }I do realise that my code probably isn't very elegant but I'm only learning!

    Hi Matt--
    I am not clear if you are saving the url with the # # around
    the text or if
    the
    data already contains the # marks.
    When you insert a link, you want to make sure you insert is
    insert into table ( link1) values ( <cfqueryparam
    cfsqltype="cf_sql_varchar"
    value='#linkvaluehere#'> )
    remember to
    1) enclose your data's value inside quotes (some databases
    are picky about
    single v. double quotes).
    2) if it IS in quotes, swap doubles for singles and see if
    that helps.
    3) make sure your data being saved is NOT double hashed like
    '##linkvalueher##'. Double ##'s tell
    Coldfusion not to treat it as a variable.
    hope his helps,
    tami
    "Mattastic" <[email protected]> wrote in
    message
    news:f9c7h0$8ub$[email protected]..
    | Hi Folks,
    |
    | I'm storing a link in a nvarchar field in SQL server,
    www.foo.co.uk, it
    looks
    | and works fine in SQL server. Problem occurs when I setup
    an ADP in Access
    and
    | insert links. Certain links have a hash symbol around them.
    so
    |
    http://www.foo.co.uk, would be #
    http://www.foo.co.uk# which is
    causing
    problems.
    |
    | Can anyone tell me why this is happening? and how to stop
    it?
    |
    | Thankyou
    |

  • Error handling in prepared statement batch

    Hi,
    For a prepared statement batch, it is not possible to know which operation failed. ... You should always perform a ROLLBACK operation in this situation.
    For a generic statement batch or callable statement batch, the update counts array is only a partial array containing the actual update counts up to the point of the error. ... You can either commit or roll back the successful operations in this situation, as you prefer.
    -- http://otn.oracle.com/docs/products/oracle9i/doc_library/release2/java.920/a96654/oraperf.htm#1056233
    But, I want to skip failed operations and continue to excecute the remains of the batch, also, I want to improve application performance, what should I do? Is there any choice?
    Best Regards,
    Kevin Zhao

    According to the Oracle docs these are not the only possible values:
    Oracle9i JDBC Developer's Guide and Reference
    Release 2 (9.2) chapter 12
    Performance Extensions
    "For a prepared statement batch, it is not possible to know which operation failed. The array has one element for each operation in the batch, and each element has a value of -3. According to the JDBC 2.0 specification, a value of -3 indicates that an operation did not complete successfully. In this case, it was presumably just one operation that actually failed, but because the JDBC driver does not know which operation that was, it labels all the batched operations as failures."
    It goes on to say that for a generic statement batch it is possible to know which failed. I would like to know if similar functionality will be available for prepared statement batches in the future.

  • Problems with Prepared Statement

    Hi,
    I am developing an Java Bean that reads from a database of Entertainments of my home city of Glasgow and displays that info to a text area. I want the User to input the type of Entertainment they want e.g. Bars or Clubs, and the name of the place they want to go and then the Java Bean displays the info of the specified place.
    The program works fine if I set the Query to display the data from the database but I want the User to define the query by thier input.
    So I used Prepared Statements, but I have error messages saying that
    Syntax Error in FROM Clause
    my code to query the database is shown below
    String query ="SELECT * FROM ? WHERE Name=?";
    PreparedStatement PresStatement=con.prepareStatement(query);
    //my input to test Database.will change to variable
    PreStatement.setString(1,"Pubs");
    PreStatement.setString(2,"Admiral");
    ResultSet rs=PreStatement.executeQuery();The Problem seems to the placholder after the FROM clause but I can't seem to fix it.
    Any Help would be greatly appreciated.
    Regards
    Brian

    just a guess here, but I'd imagine it's because of the way PreparedStatement handles Strings. Obviously, if you're using a String as part of your SQL query, you're going to want single quotes around the entire thing. Thus, the first setString() is probably trying to put single quotes around the table name, which could be causing problems.
    You don't really lose anything if you just work around this by changing your code to..
    tableName = "Pubs"; //or this is probably coming from your user
    String query ="SELECT * FROM "+tableName+" WHERE Name=?";
    PreparedStatement PresStatement=con.prepareStatement(query);
    //my input to test Database.will change to variable
    PreStatement.setString(1,"Admiral");
    ResultSet rs=PreStatement.executeQuery();

  • Count of Rows Updated with prepared statement batch

    I am using a batch of prepared statements for update operation. (pstmt.executeBatch())
    Configuration I am using
    WLS 6.1sp2 Connection pool - Oracle Thin driver - TX Datasource
    DB - Oracle 8.1.7
    The batch update works well i.e data gets updated and committed. BUT I am not
    getting back the count of number of rows updated.
    Is there any thing more required on WLS side ?
    Thanks in Advance

    The Oracle drivers do not return the updated row counts from batched updates.
    Try running the attached program with the thin driver
    java Batch oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@host:port:database user password
    You will see that returns -2, which indicates that the number of rows updated is unknown.
    This does meet the JDBC spec.
    "Harshad Nanal" <[email protected]> wrote in message news:3f8a455f$[email protected]..
    >
    I am using a batch of prepared statements for update operation. (pstmt.executeBatch())
    Configuration I am using
    WLS 6.1sp2 Connection pool - Oracle Thin driver - TX Datasource
    DB - Oracle 8.1.7
    The batch update works well i.e data gets updated and committed. BUT I am not
    getting back the count of number of rows updated.
    Is there any thing more required on WLS side ?
    Thanks in Advance[Batch.java]

  • Getting SQL errors with prepared statement in JDeveloper 10.1.3.2

    I'm using oracle JDBC driver and I connect and update just fine from the SQL Worksheet in JDeveloper.
    1) When I have more than 1 placeholder in my SQL statement, the last one is dropped so I get "Invalid column index".
    2) When I add an extra one, it prepares OK but gets "ORA-01745: invalid host/bind variable name" on execution if the placeholder is inside the SQL closing paren (this situation is showed below).
    3) When an extra one is outside the SQL closing paren, I get "ORA-00933: SQL command not properly ended"
    I'm probably missing something obvious but here is the code I'm using:
    public void insertToDB(Comment inrecord) throws Exception {
    int idx = 0;
    try {
    this.initialize();
    pstmt = conn.prepareStatement(
    "INSERT INTO COMMENTS (COMMENT_ID, " +
    "LOG_BUS_PROC_CDE, TYPE_CDE, SUBTYPE_CDE, " +
    "REF_TYP_CDE, CREATE_USER, CREATE_DATE, " +
    "UPDATED_USER, UPDATED_DATE, COMMENT_TEXT) VALUES(" +
    "TO_TIMESTAMP('?','YYYY-MM-DD HH24:MI:SS.FF3'), ?, ?, " +
    "?, ?, ?, TO_DATE(?,'MM/DD/YYYY'), NULL, NULL, ? ?)");
    pstmt.setString(++idx,inrecord.getCommentID());
    pstmt.setString(++idx,inrecord.getLogBusProcCDE());
    pstmt.setString(++idx,inrecord.getTypeCDE());
    pstmt.setString(++idx,inrecord.getSubTypeCDE());
    pstmt.setString(++idx,inrecord.getRefTypCDE());
    pstmt.setString(++idx,inrecord.getCreateUser());
    pstmt.setString(++idx,inrecord.getCreateDate());
    pstmt.setString(++idx,inrecord.getCommentTXT());
    pstmt.executeUpdate();
    conn.commit();
    this.terminate();
    catch (Exception e) {
    conn.rollback();
    this.terminate();
    throw e;
    }

    Hi,
    actually you increment the index
    pstmt.setString(++idx,inrecord.getCommentID());
    which means you never have an index of 0 but always start with 1
    Frank

  • Problems with prepared statement in MYSQL.

    I 've this code:
    String sql = "UPDATE dcr SET Fecha=?, Origen=?, Destino=?, Mensaje=?, Estado=? WHERE IDDCR=? AND IDUsuario=?";
    PreparedStatement st = cn.prepareStatement(sql);
    SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
    java.sql.Date sqlDate = java.sql.Date.valueOf(fmt.format(this.fecha));
    st.setDate(1, sqlDate);
    st.setString(2, this.origen);
    st.setString(3, this.destino);
    st.setString(4, this.mensaje);
    st.setString(5, this.estado);
    st.setString(6, this.primaryKey);
    st.setString(7, this.usuario);
    I receive a SQLException with this message "Callable statments not supported" when the line "PreparedStatement st = cn.prepareStatement(sql)" is executed.
    My JDBC Driver is "mysql-connector-java-3.0.11-stable-bin" and my server is "*MySQL 4.0.17-max"*.
    Anybody see where is the problem?
    Tnaks in advance.
    Ricardo.

    I've more information about this problem.
    If I take my code and put it in a class with a main function it works fine.
    The original code is a part of a DAO pattern object that is invoked by a servlet (is the storeObject function).
    The servlet create a record, send a native TCP/IP transaction to a external system and whit this code update the record previously created with the result of the transaction.
    The system uses connection pooling. But the conection used in create of the record is diferent from the used in this code. (It's returned to the Datasource) All objects of the database process are closed in a finaly block before return the connection. (Statements, PreparedStatements , ResultSets, etc...)
    Thanks in advance.
    Ricardo

  • Can you explain this error message with MERGE statement

    Here is the code that gives me headache.
    I give you the description of the two tables involved and the error message I get when I run a simple MERGE statement
    SQL> desc employees
    Name Null? Type
    EMPLOYEE_ID NOT NULL NUMBER(6)
    FIRST_NAME VARCHAR2(20)
    LAST_NAME NOT NULL VARCHAR2(25)
    EMAIL NOT NULL VARCHAR2(25)
    PHONE_NUMBER VARCHAR2(20)
    HIRE_DATE NOT NULL DATE
    JOB_ID NOT NULL VARCHAR2(10)
    SALARY NUMBER(8,2)
    COMMISSION_PCT NUMBER(2,2)
    MANAGER_ID NUMBER(6)
    DEPARTMENT_ID NUMBER(4)
    SQL> desc emp2
    Name Null? Type
    EMPLOYEE_ID NOT NULL NUMBER(6)
    FIRST_NAME VARCHAR2(20)
    LAST_NAME VARCHAR2(25)
    1 MERGE INTO emp2 e2
    2 USING employees e
    3 ON (e2.employee_id = e.employee_id)
    4 WHEN MATCHED THEN
    5 UPDATE SET
    6 e2.employee_id = e.employee_id,
    7 e2.last_name = e.last_name,
    8 e2.first_name = e.first_name
    9 WHEN NOT MATCHED THEN
    10 INSERT VALUES
    11 (e.employee_id,
    12 e.last_name,
    13* e.first_name)
    14 /
    ON (e2.employee_id = e.employee_id)
    ERROR at line 3:
    ORA-00904: "E2"."EMPLOYEE_ID": invalid identifier
    Any responce much appreciated

    Hi,
    Columns going to be updated should not be in 'ON clause' , try to delete the line 6 of your query. By the way, there isno sense to update e2.employee_id = e.employee_id when matched, the equality is already verified.
    Nicolas.

  • Problem with prepared statement where cluase when passing string value.Help

    I am updating a table using the following code. I am using string parameter in where clause. if I use Long parameter in where clause with ps.setLong , this code is working. Is there any special way to pass string value? Am I doing anything wrong?
    ===================
    updateMPSQL.append("UPDATE MP_Table SET ");
         updateMPSQL.append("MPRqmt = ?,End_Dt = ? ");
              updateMPSQL.append("where POS = ? ");
              System.out.println(updateMPSQL.toString());
              con     = getConnection(false) ;
              ps      = con.prepareStatement(updateMPSQL.toString());
              ps.setLong(1,MPB.getMPRqmt());
              ps.setDate(2,MPB.getEnd_Dt());
              ps.setString(3,MPB.getPos());
    result = ps.execute();
              System.out.println("Result : " + result);
    ==========
    Please help me.
    Thanks in advance.
    Regards,
    Sekhar

    doesn't Pos look like a number rather than a string variable?
    if I use Long
    parameter in where clause with ps.setLong , this code
    is working.
    updateMPSQL.append("where POS = ? ");
    ps.setString(3,MPB.getPos());

  • Ingres prepared statement error

    Hi there,
    I 'm encountering a very strange problem with a prepared statement and ingres.
    String strSQL = "select first 50 date_part('year', dtrans_date) as year, ccalled_place as place, "  +
    "count(*) as calls, " +
    "sum(nduration/60.0) as duration " +
    "from phone " +
    "where date_part('year', dtrans_date) = ? and cDest_type='C' " +
    "group by date_part('year', dtrans_date), ccalled_place " +
    "order by date_part('year', dtrans_date), calls desc";
    PreparedStatement ps = conn.prepareStatement(strSQL);          
    ps.setInt(1, 2000);
    rs = ps.executeQuery();It throws the exception:
    ca.gcf.util.SqlEx: An internal error prevents further processing of this query.
    Associated error messages which provide more detailed information about the problem can be found in the error log, II_CONFIG:errlog.log
         at ca.gcf.jdbc.DrvObj.readError(DrvObj.java:773)
         at ca.gcf.jdbc.DrvObj.readResults(DrvObj.java:629)
         at ca.gcf.jdbc.DrvPrep.<init>(DrvPrep.java:137)
         at ca.gcf.jdbc.DrvConn.getPrepStmt(DrvConn.java:786)
         at ca.gcf.jdbc.JdbcPrep.<init>(JdbcPrep.java:364)
         at ca.gcf.jdbc.JdbcConn.createPrep(JdbcConn.java:1550)
         at ca.gcf.jdbc.JdbcConn.prepareStatement(JdbcConn.java:1380)
         at TestIngresDB.query(TestIngresDB.java:37)
         at TestIngresDB.<init>(TestIngresDB.java:9)
         at TestIngresDB.main(TestIngresDB.java:55)This is exactly at the line:
    ps = conn.prepareStatement(strSQL);Checking Ingres' error log:
    FREEFALL: 32867             , 12f678e0]: Thu Dec  2 07:01:57 2004 E_SC0207_UNEXPECTED_ERROR    Facility returned an undocumented error.
    FREEFALL: 32867             , 12f678e0]: ULE_FORMAT: Couldn't look up message 0 (reason: ER error 10902)
    E_CL0902_ER_NOT_FOUND   No text found for message identifier
    FREEFALL: 32867             , 12f678e0]: Thu Dec  2 07:01:57 2004 E_SC0215_PSF_ERROR   Error reHowever, other prepared statements like this work fine, e.g.:
    String sqlStr = "SELECT * FROM Stock WHERE Item_Number = ?";
    PreparedStatement pstmt = con.prepareStatement(query);
    pstmt.setInt(1, 2);
    ResultSet rs = pstmt.executeQuery();Sorry if this posting is not appropriate here, but I really don't know if this has something to do with JDBC or Ingres driver itself. Note that the query runs perfectly ok when run from Ingres VisualDBA.
    Thanks,
    John.

    Your prepared statement looks like
    select first 50 date_part('year', dtrans_date) as year, ccalled_place as place, count(*) as calls, sum(nduration/60.0) as duration from phone where date_part('year', dtrans_date) = ? and cDest_type='C' group by date_part('year', dtrans_date), ccalled_place order by date_part('year', dtrans_date), calls desc
    I am not sure what this "first 50" is for?
    ***Annie***

  • Prepared Statement with ORDER BY

    I am trying to use order by with prepared statement but it is not ordering.
    String sql = "SELECT * FROM MATERIAL WHERE (LOWER(NAMEE) LIKE ('%' || ? || '%') ORDER BY ? ";
    PreparedStatement ps=CM.getStatement(sql);
    ps.setString(1,p);
    ps.setString(2,sort);
              ResultSet r = ps.executeQuery();
    Can any one tell me how do I use prepared statement with order by

    You can not parameterize column names and such, only literals. You should build the ORDER BY clause dynamically.

  • Prepared statements related problem

    Hi,
    i have this strange problem with prepared statements i think.
    When i execute an insert query without prepared statements i works fine (always), when i use prepared statements it sometimes gives a db error saying i'm trying to insert a null value.
    The problem is that I'm not!!!
    If i were why does it work sometimes?
    It may be a bug but i don't know where to look for it... is it a prepared statements, application server or db2 problem?

    This is the code...
         public void insertArticolo(Articolo item) throws Exception {
              PreparedStatement ps = null;
                   try {          
                        StringBuffer sql = new StringBuffer("insert into RUW.RUWT1_ARTICOLO (");
                        sql.append("C_ENTE, C_CONCESSIONE,N_ANNO_RUOLO,N_PROGR_RUOLO,N_PARTITA,N_PROGR_PARTITA,N_PROGR_TRIBUTO, ");
                        sql.append("C_TRIBUTO, C_TIPO_UFF,C_UFFICIO,");
                        sql.append("C_TIPO_IMP, N_ANNO_IMP, L_CARICO, S_ARTICOLO");
                        sql.append(") values (");
                        sql.append("?" + ", ");
                        sql.append("?" + ", ");
                        sql.append("?" + ", ");
                        sql.append("?" + ", ");
                        sql.append("?" + ", ");
                        sql.append("?" + ", ");
                        sql.append("?" + ", ");
                        sql.append("?" + ", ");
                        sql.append("?" + ", ");
                        sql.append("?" + ", ");
                        sql.append("?" + ", ");
                        sql.append("?" + ", ");
                        sql.append("?" + ", ");
                        sql.append("?");
                        sql.append(")");
                        ps = connectionCreatePreparedStatement(sql.toString());
                        System.out.println(sql.toString());
                        KeyArticolo keyArticolo = item.getKeyArticolo();
                        KeyPartita keyPartita = keyArticolo.getKeyPartita();
                        Ente ente = keyPartita.getKeyRuolo().getEnte();
                        System.out.println("/"+ ente.getCodEnte()+ "/");
                        System.out.println("/"+ keyPartita.getKeyRuolo().getConcessione().getCodConc()+ "/");
                        System.out.println("/"+ keyPartita.getKeyRuolo().getAnnoRuolo()+ "/");
                        System.out.println("/"+ keyPartita.getKeyRuolo().getProgRuolo()+ "/");
                        System.out.println("/"+ keyPartita.getNumPartita()+ "/");
                        System.out.println("/"+ keyPartita.getProgPartita()+ "/");
                        System.out.println("/"+ item.getKeyArticolo().getProgArticolo()+ "/");
                        System.out.println("/"+ item.getCodEntrata()+ "/");
                        System.out.println("/"+ ente.getTipoUfficio()+ "/");
                        System.out.println("/"+ ente.getCodUfficio()+ "/");
                        System.out.println("/"+ item.getTipoImposta()+ "/");
                        System.out.println("/"+ item.getAnnoImposta()+ "/");
                        System.out.println("/"+ item.getCaricoOrigine()+ "/");
                        if (item.getDescArticolo().equals("")) {
                             item.setDescArticolo(" ");
                        System.out.println("/"+ item.getDescArticolo()+ "/");
                        ps.setLong(1,ente.getCodEnte());
                        ps.setLong(2,keyPartita.getKeyRuolo().getConcessione().getCodConc());
                        ps.setLong(3,keyPartita.getKeyRuolo().getAnnoRuolo());
                        ps.setLong(4,keyPartita.getKeyRuolo().getProgRuolo());
                        ps.setLong(5,keyPartita.getNumPartita());
                        ps.setLong(6,keyPartita.getProgPartita());
                        ps.setLong(7,item.getKeyArticolo().getProgArticolo());
                        ps.setString(8,item.getCodEntrata());
                        ps.setString(9,ente.getTipoUfficio());
                        ps.setString(10,ente.getCodUfficio());
                        ps.setString(11,item.getTipoImposta());
                        ps.setLong(12,item.getAnnoImposta());
                        ps.setLong(13,item.getCaricoOrigine());
                        ps.setString(14,item.getDescArticolo());
                        ps.executeUpdate();
                   catch (Exception e) {
                        e.printStackTrace();
                        connectionCloseStatement(ps);
                        throw e;
              }and this is the result of the systemout
    [10/03/06 14.07.07:051 CET] 76357635 SystemOut O insert into RUW.RUWT1_ARTICOLO (C_ENTE, C_CONCESSIONE,N_ANNO_RUOLO,N_PROGR_RUOLO,N_PARTITA,N_PROGR_PARTITA,N_PROGR_TRIBUTO, C_TRIBUTO, C_TIPO_UFF,C_UFFICIO,C_TIPO_IMP, N_ANNO_IMP, L_CARICO, S_ARTICOLO) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    /13199/
    /66/
    /2002/
    /1564/
    /28330/
    /1/
    /2/
    /0997/
    /120/
    /2002/
    /11900/
    / /

Maybe you are looking for