SetString in Prepared Statement

Help!
I am trying to use a prepared statement and use a setString. It seems to work when I use a value as the parameter, but when I pass it a variable I get an error. Any ideas???
THIS WORKS.....
String buffer;
String selectStmt1 = "SELECT veh_key_i FROM yzdbdat.mxtp010_veh " +
"WHERE veh_chass_no = ?";
PreparedStatement selectVehKey = connection.prepareStatement(selectStmt1);
selectVehKey.setString(1,"2H412152");
ResultSet getVehicle = selectVehKey.executeQuery();
THIS DOESN'T...I GET A RIGHT TRUNCATION ERROR
String buffer;
String selectStmt1 = "SELECT veh_key_i FROM yzdbdat.mxtp010_veh " +
"WHERE veh_chass_no = ?";
PreparedStatement selectVehKey = connection.prepareStatement(selectStmt1);
selectVehKey.setString(1,buffer);
ResultSet getVehicle = selectVehKey.executeQuery();
THANKS!!

A right truncation error? I would have expected a NullPointerException, since you haven't assigned anything to that variable. But if your real code does assign something to it, then probably it is too long to fit in the database column.

Similar Messages

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

  • String length limitation on setString() in prepared statement

    Hi,
    Is any body aware of the length of string that can be passed to setString() method of prepared statement. I am getting an error "Data size bigger than max size for this type" if the string length is more than 2000 chars. I am using jdk 1.2.2 for running the application.
    Thanks in advance.
    Nihar.

    Please use the following method. It worked for me.
    PreparedStatement pstmt = ......;
    String str = .....;
    pstmt.setObject(index,str,java.sql.Types.LONGVARCHAR);
    Ranjan.

  • Use of Prepared Statement in adf

    Hi Experts,
    I am confused with the Use of prepared statement in adf.
    My use case is ,
    I have to update a table from every page in my application under certain conditions.
    My question is ,
    whether I have to create the VO iterator binding in every page and by calling the createinsert and insert the data in to the table or
    use a common method in the Application module impl
    which is using a prepared statement,(which is not even creating the ViewObject ) like
    PreparedStatement st = null;
    String sql = "INSERT INTO hr.departments (DEPARTMENT_ID,    DEPARTMENT_NAME,   MANAGER_ID,   LOCATION_ID) VALUES (seq,?,?,?)";
                st=getDBTransaction().createPreparedStatement(sql,0);
                st.setString(1, name);
                st.setString(2, mgr_id);
                st.setString(3, Loc_id);
                st.execute();
    getDBTransaction().commit();which is the best approach?
    Studio Edition Version 11.1.1.2.0
    Ranjith

    Ranjith,
    Without further understanding the use case, there's not really much difference between the two approaches. In both cases, you'd have a binding in the page definition (either an iterator binding for the VO or a method binding for the AM service method). Both will use bind variables. The main difference I can see is that, depending on how you have configured your AM pooling settings, the VO method will incur fewer parses in the DB because the AM will cache prepared statements for you.
    John

  • When to use prepared statement in java?

    Hi all,
    If we have query like select * from {tablename} (Here tablename is the variable) then will the use of prepared staement improve the performance? My guess is use of statement in this case is a better option rather than prepared statement as the tablename may change for every other query.I think are not useful if tablename changes.They are useful only when the where clause has dynamic values.

    cantor wrote:
    Are you sure that your approach is possible? The next example causes exception for me.
    PreparedStatement ps = conn.prepareStatement("select * from ?");
    ps.setString(1, "TABLE_NAME");
    ps.executeQuery();
    I didn't say that he should solve it in that way. He should create one prepared statement like this "select a, b, c from tablename1" and another prepared statement when he wants to execute "select d, e, f from tablename2"
    >
    And as I understand, this code will not improve perfomance (and even will not work). As I said it can.
    Prepared statements make possible usage compiled queries inside DB. When DB gets prepared statement call, it need to parse it only once. And it can collect some statistic to improve execution plan. But when table name is not specified, this approach will not work.Yes it might. There are database drivers that can cache prepared statements and it's isn't likely that he executes that query on more than e.g. 20 tables?
    The database can also cache compiled statements in a cache.
    Kaj

  • Pass table name as parameter in prepared Statement

    Can I pass table name as parameter in prepared Statement
    for example
    select * from ? where name =?
    when i use setString method for passing parameters this method append single colon before and after of this parameter but table name should be send with out colon as SQL Spec.
    I have another way to make sql query in programing but i have a case where i have limitation of that thing so please tell me is it possible with prepared Statment SetXXx methods or not ?
    Thanks
    Haroon Idrees.

    haroonob wrote:
    I know ? is use for data only my question is this way to pass table name as parameterI assume you mean "how can I do it?" As I have already answered "is this the way?" with no.
    Well, I would say (ugly as it is) String concatenation, or stored procedures.

  • Problem in prepared Statement

    hi,
    i have used following prepared Statement for the update in database.
    Can any one tell me that,How can i use date in following method.
    I have 4 field for date as given below:(BOLD shown)
    I have used String in that place.
    It is not working.
    PreparedStatement pstatement = conn.prepareStatement(
    "UPDATE sec_mast SET catg_code=?, vou_no=?, vou_date=?, vou_amt=?, due_date1=?, due_date2=?, mat_date=? where sec_no=? ");
    pstatement.setInt(1,Integer.parseInt(request.getParameter("catg_code")));
    pstatement.setString(2,request.getParameter("vou_no"));
    pstatement.setString(3,request.getParameter("vou_date"));
    pstatement.setInt(4,Integer.parseInt(request.getParameter("vou_amt")));
    pstatement.setString(5,request.getParameter("due_date1"));
    pstatement.setString(6,request.getParameter("due_date2"));
    pstatement.setString(7,request.getParameter("mat_date"));
    pstatement.setInt(8,Integer.parseInt(request.getParameter("sec_no")));
    int rowCount = pstatement.executeUpdate();
    conn.setAutoCommit(false);
    conn.setAutoCommit(true);
    plz help me

    thanx for u r reply.
    MY whole code is shown as below:
    This page is for the updating the values in database..
    <html>
    <body>
    <table>
    <tr>
    <td>
    <%@ page import="javax.servlet.*" %>
    <%@ page import="javax.servlet.http.*" %>
    <%@ page language="java" import="java.sql.*" %>
    <%
    try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection conn=DriverManager.getConnection("jdbc:odbc:pf","scott","ttlscott");
    System.out.println("got connection");
    %>
    <%
    String action = request.getParameter("action");
    // Check if an update is requested
    if (action != null && action.equals("update")) {
    conn.setAutoCommit(false);
    PreparedStatement pstatement = conn.prepareStatement(
    "UPDATE sec_mast SET sec_no=? , catg_code=?, face_val=?, pur_val=?, int_paid=?, int_recd=?, brkr=?, vou_no=?, vou_date=?, vou_amt=?, due_date1=?, due_date2=?, lf_no=?, mat_date=? where tot_val=? ");
    pstatement.setInt(1,Integer.parseInt(request.getParameter("sec_no")));
    pstatement.setInt(2,Integer.parseInt(request.getParameter("catg_code")));
    pstatement.setInt(3,Integer.parseInt(request.getParameter("face_val")));
    pstatement.setInt(4,Integer.parseInt(request.getParameter("pur_val")));
    pstatement.setInt(5,Integer.parseInt(request.getParameter("int_paid")));
    pstatement.setInt(6,Integer.parseInt(request.getParameter("int_recd")));
    pstatement.setInt(7,Integer.parseInt(request.getParameter("brkr")));
    pstatement.setString(8,request.getParameter("vou_no"));
    pstatement.setString(9,request.getParameter("vou_date"));
    pstatement.setInt(10,Integer.parseInt(request.getParameter("vou_amt")));
    pstatement.setString(11,request.getParameter("due_date1"));
    pstatement.setString(12,request.getParameter("due_date2"));
    pstatement.setString(13,request.getParameter("lf_no"));
    pstatement.setString(14,request.getParameter("mat_date"));
    pstatement.setInt(15,Integer.parseInt(request.getParameter("tot_val")));
    int rowCount = pstatement.executeUpdate();
    conn.setAutoCommit(false);
    conn.setAutoCommit(true);
    %>
    <%
    // Create the statement
    Statement statement = conn.createStatement();
    ResultSet rs = statement.executeQuery
    ("SELECT * from sec_mast ");
    %>
    <%
    // Iterate over the ResultSet
    while ( rs.next() ) {
    %>
    <tr>
    <form action="security_update.jsp" method="get">
    <input type="hidden" value="update" name="action">
    <td><input value="<%= rs.getInt("sec_no") %>" name="sec_no"></td>
    <td><input value="<%= rs.getInt("catg_code") %>" name="catg_code"></td>
    <td><input value="<%= rs.getInt("face_val") %>" name="face_val"></td>
    <td><input value="<%= rs.getInt("pur_val") %>" name="pur_val"></td>
    <td><input value="<%= rs.getInt("int_paid") %>" name="int_paid"></td>
    <td><input value="<%= rs.getInt("int_recd") %>" name="int_recd"></td>
    <td><input value="<%= rs.getInt("brkr") %>" name="brkr"></td>
    <td><input value="<%= rs.getInt("tot_val") %>" name="tot_val"></td>
    <td><input value="<%= rs.getString("vou_no") %>" name="vou_no"></td>
    <td><input value="<%= rs.getDate("vou_date") %>" name="vou_date"></td>
    <td><input value="<%= rs.getInt("vou_amt") %>" name="vou_amt"></td>
    <td><input value="<%= rs.getDate("due_date1") %>" name="due_date1"></td>
    <td><input value="<%= rs.getDate("due_date2") %>" name="due_date2"></td>
    <td><input value="<%= rs.getString("lf_no") %>" name="lf_no"></td>
    <td><input value="<%= rs.getDate("mat_date") %>" name="mat_date"></td>
    <td><input type="submit" value="Update"></td>
    </form>
    </tr>
    <%
    %>
    </table>
    <%
    // Close the ResultSet
    rs.close();
    // Close the Statement
    statement.close();
    // Close the Connection
    conn.close();
    } catch (SQLException sqle) {
    out.println(sqle.getMessage());
    } catch (Exception e) {
    out.println(e.getMessage());
    %>
    </td>
    </tr>
    </body>
    </html>

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

  • Prepared statement help

    Hello all!
    I am trying to get this prepared statement to work but am getting an error that I cant understand.
    Basically I have a class file that the ps resides in. I am calling the ps from a jsp.
    Here is the code:
    public void recordUsage(String userid, String ipaddress, String page, String filename)
           String insertStatement = "INSERT INTO usageLog(userId,ipAddress, localTime, page, fileName) VALUES(?,?,?,?,?)";
                try
                {   java.util.Date currentDate=new java.util.Date();//Create a date object for the timestamp
                    java.sql.Timestamp ts=new java.sql.Timestamp(currentDate.getTime());//Create the timestamp from the above date object.
                    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                    objConn = java.sql.DriverManager.getConnection("jdbc:odbc:sensorWeek","","");
                    PreparedStatement ps = objConn.prepareStatement(insertStatement);
                    ps.setString(1, userid);
                    ps.setString(2, ipaddress);
                    ps.setTimestamp(3, ts);
                    ps.setString(4, page);
                    ps.setString(5, filename);
                    ps.executeUpdate();
                    objConn.commit();
                    ps.close();
                    objConn.close();
                    System.out.println("recordusage method called");
                catch (SQLException s)
                    System.err.println("DataBase PROBLEM");
                    s.printStackTrace();
                catch (Exception e)
                        System.err.println("Error in recordUsage method");
                        e.printStackTrace();
    }Here is the error generated:(I hate to dump this on you)
    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.record(Ljava/lang/String;Ljava/lang/String;)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.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.record(Ljava/lang/String;Ljava/lang/String;)V
         at org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:536)
         at org.apache.jsp.download_jsp._jspService(download_jsp.java:93)
         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)
    TIA!!

    And what makes you think that the above code is causing the problem?

  • Error with ExecuteQuery() in prepared statement

    Hello,
    i' m a new one at java. I' m trying to build a web application in jsp and i have a problem in a simple at log in authentication.
    My code is this:
    <html>
    <head>
    <title>Welcome to the online Boat Shop, Inc.</title></head>
    <body>
    <%@ page language ="java" import = "java.io.*, java.lang.*, java.sql.*" %>
    <% try
    String strUsername = request.getParameter("USERNAME");
    String strPassword = request.getParameter("PASSWORD");
    Class.forName ("org.apache.derby.jdbc.ClientDriver");
    Connection myConn = DriverManager.getConnection("jdbc:derby://localhost:1527/boatsdb","tony", "logo");
    String strSQL = "SELECT USERNAME, PASSWORD FROM BOATDB where USERNAME = ? and PASSWORD = ?";
    PreparedStatement stmt = myConn.prepareStatement(strSQL);
    stmt.setString(1, "USERNAME");
    stmt.setString(2, "PASSWORD");
    ResultSet myResult = stmt.executeQuery(strSQL);
    if(myResult.next()){
    out.println("Login Succesful! A record with the given user name and password exists");
    } else {
    out.println("Login Failed. No records exists with the given user name and password");
    myResult.close();
    stmt.close();
    myConn.close();
    } catch(Exception e){
    out.println(e);
    %>
    </body>
    </html>
    The problem is that prepared statement doesn't support executeQuery() method and i can find any solution. The error is this:
    java.sql.SQLException: Method 'executeQuery(String)' not allowed on prepared statement. I already have some data in my database so that it can return results.
    Thank you.
    Edited by: antonis on May 3, 2008 6:13 AM

    thank you, that was the problem. It seems that i have also done mistakes in passing the username and password from the forms to the database for checking, because the message that i get always when i log is that there is no user with this username kai password.
    <form method=GET action=log1.jsp>
    <font size=5> Username <input type=text name="USERNAME" size=20>
              </font>
              <br>
              <font size=5> Password <input type=text name="PASSWORD" size=20>
              </font>
              <br>
              <input type=submit name=action value="Submit">
    </form>
    That's the forms and combined with the code in the fist post should have worked. Any ideas?
    thanks again.

  • Using partition in prepared statement

    Hello,
    I am connecting to an oracle 9i database and write a prepared statement like
    String query = "SELECT * FROM ADM.TABLE1 PARTITION (TABLE1_?)";
    PreparedStatement pstmt = dbConnection.prepareStatement(query);
    pstmt.setString(1, "20" + callDate); // Partitions are like TABLE1_20030605
    ResultSet rs = pstmt.executeQuery();
    I get this error ORA-00933: SQL command not properly ended
    Any ideas if i am substituting the value correctly or if this is the right way to use prepared statement ?

    It is the wrong way to use a prepared statement.
    You will need to create the string dynamically.

  • Binding in Prepared Statement is not working with Microsoft SQL Server JDBC

    I ran the following program with sqljdbc4.jar in the class path. There is data in the EMPLOYEE table for the employee name DEMO but the following program is not retrieving data for DEMO. When the same program was run with Merlia.jar in the class path, it was retrieving data for DEMO.
    Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
    Connection con = DriverManager.getConnection("jdbc:sqlserver://SERVER23:5000;databaseName=TESTDB", "SYSADM", "SYSADM");
    String sqlSele = "SELECT * FROM EMPLOYEE WHERE EMPNAME like ?" ;
    PreparedStatement sts = con.prepareStatement(sqlSele);
    sts.setString(1, "DEMO" );
    ResultSet rs = sts.executeQuery();
    while(rs.next())
    System.out.println("driverConn.main()" + rs.toString());
    catch(Exception e)
    System.out.println(e);
    e.printStackTrace();
    Can someone help me out from this issue.

    This is the program that I used for testing the behaviour of prepared statement with sqljdbc4.jar. Also included the code for Merlia.jar.
    import java.sql.*;
    public class driverConn {
         public static void main(String [] a)
              try{
              Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
              //Class.forName("com.inet.tds.TdsDriver");
              Connection con = DriverManager.getConnection("jdbc:sqlserver://SERVER23:5000;databaseName=TESTDB", "SYSADM", "SYSADM");
              //Connection con = DriverManager.getConnection("jdbc:inetdae7a:SERVER23:5000?database=TESTDB", "SYSADM", "SYSADM");
              String sqlSele = "SELECT * FROM EMPLOYEE WHERE EMPNAME like ?" ;
              //String sqlSele = "SELECT * FROM EMPLOYEE WHERE EMPNAME like ‘%DEMO%’”;
              PreparedStatement sts = con.prepareStatement(sqlSele);
              sts.setString(1, "DEMO" );
              //sts.setString(1, "%DEMO%" );          
              java.sql.ResultSet rs = sts.executeQuery();          
              while(rs.next())
                   System.out.println("EMPNAME is " + rs.getString(“EMPNAME”) + “”);                    }
              catch(Exception e)
                   System.out.println(e);
                   e.printStackTrace();
    Following are the specifications:
    Version of the Driver:
    Microsoft JDBC Driver 4.0 for SQL Server CTP3
    Downloaded the driver using the link http://www.microsoft.com/download/en/details.aspx?id=11774
    Java Version:
    Java 1.7.0_02
    Database Version:
    Microsoft SQL Server 2008 (SP2) - 10.0.4000.0 (X64)

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

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

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

  • Problem in inserting to MS Access using prepared statement

    I am inserting a record in MS Access db and I am using prepared statement. I am encountering an error.... any help I would really appreciate it. So much time figuring out what the problem is....
    ConvertText contxt = new ConvertText();
    String bday = (String)cbYear.getSelectedItem() +
    cbMonth.getItemCount()+(String)cbDay.getSelectedItem();
    try{
    // load MySQL driver
    Class.forName(driver);
    // Setup connection to DBMS
    Connection conn = DriverManager.getConnection(url);
    // Create statement     
    Statement stmt     = conn.createStatement();
    PreparedStatement insertPersons = conn.prepareStatement(
            "INSERT INTO PERSONS VALUES(" +
         "FIRST_NAME               = ?," +
         "LAST_NAME              = ?," +
         "MIDDLE_NAME               = ?," +
         "NICKNAME              = ?," +
         "GENDER              = ?," +
         "MARITALSTATUS           = ?," +
         "AGE                    = ?," +
         "BIRTHDATE                   = ?," +
         "ADDRESS                  = ?," +
         "RES_PHONE_NUMBER        = ?," +
         "OFFICE_PHONE_NUMBER     = ?," +
         "CELL_NUMBER               = ?," +
         "COMPANY_NAME               = ?," +
         "EMAIL_ADDRESS               = ?," +
         "TIMESTAMP               = ?)"
              insertPersons.setString   (1, tfFirstName.getText());
              insertPersons.setString   (2, tfLastName.getText());
              insertPersons.setString   (3, tfMiddleName.getText());
              insertPersons.setString   (4, tfNickName.getText());
              insertPersons.setString   (5, (String)cbGender.getSelectedItem());
              insertPersons.setString   (6, (String)cbMaritalStatus.getSelectedItem());
              insertPersons.setInt      (7, contxt.formatStringToInt(tfAge.getText()));
              insertPersons.setDate     (8, contxt.formatStringToSQLDate(bday));
              insertPersons.setString   (9, tfAddress.getText());
              insertPersons.setString   (10,tfResPhoneNumber.getText());
              insertPersons.setString   (11,tfOffPhoneNumber.getText());
              insertPersons.setString   (12,tfCellNumber.getText());
              insertPersons.setString   (13,tfCompanyName.getText());
              insertPersons.setString   (14,tfEmailAddress.getText());
              insertPersons.setTimestamp(15, new Timestamp(System.currentTimeMillis()));          
              insertPersons.executeUpdate();
              conn.close();          
    JOptionPane.showMessageDialog(null,"Record Inserted!", "INSERT",
                        JOptionPane.INFORMATION_MESSAGE);
    }catch (SQLException ex){
    System.err.println("==> SQLException: ");
    System.out.println("Message:   SQL Exception");
    System.out.println("Message:   " + ex.getMessage ());
    System.out.println("SQLState:  " + ex.getSQLState ());
    System.out.println("ErrorCode: " + ex.getErrorCode ());
    JOptionPane.showMessageDialog(null, ex.getMessage() + ex.toString(),"Error", JOptionPane.INFORMATION_MESSAGE);
    }catch(Exception ex){
    }          ERROR Displayed:
    [Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 30. java.sql.SQLException     

    Hi cruzdhel,
    Your SQL looks incorrect to me.
    I am not familiar with that syntax.
    I think it should be like this:
    PreparedStatement insertPersons =
    conn.prepareStatement("INSERT INTO PERSONS (FIRST_NAME," +
                                               "LAST_NAME," +
                                               "MIDDLE_NAME," +
                                               "NICKNAME," +
                                               "GENDER," +
                                               "MARITALSTATUS," +
                                               "AGE," +
                                               "BIRTHDATE," +
                                               "ADDRESS," +
                                               "RES_PHONE_NUMBER," +
                                               "OFFICE_PHONE_NUMBER," +
                                               "CELL_NUMBER," +
                                               "COMPANY_NAME," +
                                               "EMAIL_ADDRESS," +
                                               "TIMESTAMP)" +
    "values (?," +
            "?," +
            "?," +
            "?," +
            "?," +
            "?," +
            "?," +
            "?," +
            "?," +
            "?," +
            "?," +
            "?," +
            "?," +
            "?," +
            "?)");Hope this helps.
    Good Luck,
    Avi.

  • Prepared statement

    Hi All,
    I am executing a sql statement(using SQL server) given below
    "Select * from table_name where column1 LIKE 'a%'"
    I want to search for all records in "table_name" where "column1" starts with character "a"
    I want a prepared statement equivalent to above sql------
    I am currently using ------the following code---
    stmt = "Select * from table_name where column1 LIKE ?"
    and
    stmt.setString(1,'a%');
    But it is not working ...Can some help me out in this prepared statement

    How does 'Like' keyword work in prepared statement. It is not working when I am trying to use the following statements....
    squery = "SELECT COUNT(*) As COUNT FROM table_name WHERE RTRIM(LTRIM(column1)) LIKE ?";
    pstmt = con.prepareStatement(sQuery)
    pstmt.setString(1,"xyx");
    pstmt.executeQuery();
    And I am trying to search for records having the value of "xyz" for the column "column1" in table "table_name".
    I am getting 0 records eventhough there are records in database....
    And I am not getting any exception.
    Can someone help me on this?

Maybe you are looking for

  • Oracle 8.1.6 on HP-UX 11.0 - installation problem

    We have been trying to install ORACLE 8i (8.1.6) release 2 on a HP_UX 11.0 Server, and faced errors when we started installation.` As per the install notes, we had to mount the CD media using pfs_mount with file system type set to rrip(i.e.iso9660 fo

  • PO and Goods receipt flag table

    Hi all, I want to select POs for which Goods receipt is not created. Is there any table which stores the PO number and GR flag indication for created or not created. And the table should contain date of creation for PO too. Thanks Ricky

  • I cant download apps on my ipod

    please help! i cant download apps on my ipod! once ive pressed install, it just goes to the grey loading app icon and it stays like that until i switch my ipod off. i dropped my ipod about 3 monthes ago and a bit of the corner chipped out so im not s

  • Im unable to login when i switch on the laptop? please help me out.

    hello, yesterday I installed os yosmite  on MacBook pro. today im unable to login when I switch  on, my laptop. please help me out as soon as.

  • Deactivation didn't work!!

    I deactivated my old lap top before installing photoshop elements 9 on the new lap top, prior to going away on a 4 month overseas holiday.  It worked ok when I tested it before I left - now it says I need to deactivate one of the computers which are