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.

Similar Messages

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

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

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

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

  • 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();

  • 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();
      }

  • 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

  • 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());

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

  • Oracle Prepared Statement - 8.1.7 JDBC type II Driver

    Hi,
    I have a strange problem.
    I do a query using a prepared statement and there are no matching results.
    I change this to hardcoded SQL Statement and pass in the same value a row of record is returned
    I change this to Statement and pass in the input a row of record is returned.
    This is puzzling. There seems to be a problem with Prepared Statement and I can't see why that fails.
    The Stmt looks like this
    PreparedStatement id is defiend as a char in the database
    Code Snippet:
    SQL = Select * from employee where id = ?;
    pstmt.setString(1,'value');
    Hardcoded SQL:
    select * from employee where id = 'value';
    Statement Impl:
    String var = "value";
    "select * from employee where id = '" + var+ "'";
    Would appreciate if somebody can explain what's happening. To me it is bizarre!
    Thanks,
    Manglu

    Update to problem
    I have the latest (classes12.zip) JDBC drivers from Oracle.
    We are running Oracle 8.1.6 and converting to Oracle 8.1.7.
    This works the same with both.
    Example, I have a column (char(10)) with trailing spaces. i.e. '39 '.
    When I perform a Prepared Statement with that column in the where clause, it returns no result rows.
    When I perform a standard statement with that column in the where clause, it returns rows.
    When I define a column char(2) and use it in the where clause it works fine.
    When I define a column varchar2(10) and load it with data like '39', it works fine.
    When I define a column varchar2(10 and load it with data like '39 ', it does not work.
    When I execute this same Prepared Statement through the jdbc:odbc bridge it works fine.
    I cannot change the definition of the columns as they are foreign key data. What is the problem here? Any help is appreciated.
    If you need further information please feel free to contact me.

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

  • Escape Characters - simulate the setString from Prepared Statements

    I would like to see what the value of setString() is for a given prepared statement call.
    Because of reasons that would take me to long to explain that I cannot use preparedstatements with their parameters - I need a way to execute a query like the following:
    String query = "insert into blahtable (somestring) values (\"asdfds\'\s sdsfdasfd \"\& ...\");
    PreparedStatement stmt = connection.prepareStatement(query);
    I know prepared statements can take care of this, but I want to know and write the query as above without the need of prepared statements help for string.
    Below is an example with prepared statement - but not what I want to do
    For example:
    String oddstringwithunusalcharacters = "...";
    String query = "insert into blahtable (somestring) values (?)";
    PreparedStatement stmt = connection.prepareStatement(query);
    stmt.setString(1, oddstringwithunusalcharacters);
    I would like to see what the actual query looks like and what the actual string was passed:
    --> insert into blahtable (something) values ("asdfds\'\s sdsfdasfd \"\& .... ")
    It is not sufficient enough for me to escape quotes and apostrophes because there maybe other unusual characters that I do not know of since the string is passed by an unknown source.
    Thank you in advance

    PreparedStatements actually doesn't escape quotes. It basically precompiles statements in the DB and only passes the values to the DB.
    But if you're using a plain vanilla SQL statement where you quote the string with a single quote ' then you need to escape all occurrences of exactly the same single quote ' in the actual String value. If you for example quote the string with an apostrophe ` then you just need to escape all occurrences of exactly the same apostrophe ` in the actual String value. And so on. It is nothing more than logical, is it?

  • Disadvantages in prepared statement

    hi
    i could not tell the answer for the following question in my interview can u pleae tell me the answer for this question
    one of the disadvantages with prepared statement in jdbc?

    I have no idea what WorkForFood is talking about.Sorry, perhaps an example will help clarify:
    Using a PreparedStatement using two replacement parameters:
    String sql = "SELECT COL1 FROM MYTABLE WHERE COL1 = ? AND COL2 = ?";
    ps.setSetring("WORK");
    ps.setString("FORFOOD");Contrasted against a Statement using literals:
    "SELECT COL1 FROM MYTABLE WHERE COL1 = 'WORK' AND COL2 = 'FORFOOD'";When you execute these two queries, they can generate different explain plans, for example the Statement may use an index while the PreparedStatement may attempt a full table scan. The optimizer is choosing a more efficient explain plan for the Statement because it has more information on which to make a decision (the literal values). A full table scan will be significantly slower then using an index to return the same results. In some databases, you can provide hints, but in some cases, the only way to get this query to use an index is to provide the actual values WORK and FORFOOD in the query itself. When using literals rather then replacement parameters it should be more efficient to use Statement then PreparedStatement (see jschell's list #1). So, in these cases, you should use a Statement rather then a PreparedStatement to get best performance from your query. And again, this issue comes up very infrequently but can be quite debilitating to an applications performance when it does occur.

Maybe you are looking for

  • OIM 11gr2 On-behalf removal of accounts/entitlements

    Hi, We have a requirement with our client where a user can request for removal of accounts/entitlements on behalf of other user. We understand add request process onbehalf of some user but not sure about onbehalf removal process. Please let me know i

  • Differences between AIR 3.4 & 3.5 - iOS

    I've been having big problems trying to get a sucessful build for iOS for a swf with 2 ANEs using AIR 3.5. Does anyone know if there are any differences between 3.4 and 3.5 that would cause a major slow down/crash in iOS applications compiled in 3.5?

  • Publishing problem! Disappearing content...

    Would appreciate any assistance. I am trialing DW CS3 on new desktop using Vista Business. My ISP has provided al the remote info and connection is working and my site has been properly defined. My problem begins just seconds after i upload. It does

  • LG G2 mp4/h.264 not working on LG G2

    Mp4/h.264 videos(All websites) do not play properly on the LG G2 with KitKat 4.4.1 or 4.4.1. I have tried both the regular Firefox (32.0.3) and Beta(33.0), both seem to be having the issue. Playback works fine using mobile Chrome. Please also note, I

  • [SOLVED] UEFI boot configuration using efibootmgr

    Hello All, I've been having a very frustrating time with efibootmgr on my HP Laptop. I've been searching around for some information regarding the OS Bootmanager in UEFI boot and cannot find anything that works for me. I'm trying to get efibootmgr to