2 questions in PreparedStatement in JSP

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

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

Similar Messages

  • Beginner's question: how to call JSP

    Hi,
    Is the following a right way to call a JSP?
    GET /app/im/iClient.jsp?user=[email protected]&pass=welcome HTTP/1.1
    Host: st5.abc.com
    I am trying to manually send a HTTP request. I am sure the directory is right, but no response. Should I use "POST" instead of "GET"?
    Thank you!

    I dont believe that... If you're trying to get a response InputStream, or the response formatted as some object, for a request to an HTTP server, and you are just now writing Socket connection stuff, then you can just replace that with URLConnection and let it do the work given a URL.
    Otherwise, you should already have a class which uses Sockets internally to get what you want, and you shouldn't be asking us this question because it should take a URL and make the connection and give you what you want...
    I don't see any other possible "stage" at which you could be at that you need to a) use Sockets over URLConnections, b) need to know the details of HTTP, and c) can't change one or the other.

  • How to write Question paper program in jsp....

    Hi..,
    This is sure from india. I would like to develop online examination project. Everything is ok. But i have a problem at deveop of question paper. I have 10 questions in my database. I would like display those questions one by one. How can i done this job. Please any one guide me. Because, i am new to this concept.
    with regards
    sure..)-

    First you need to extract all the question from database..
    Then put all of those questions in any of collection object...
    Then set this collection object in request as attribute..
    Keep this object in request till all question are not shown(you can eliminate questions after the have been asked)..
    Code might be like this.
    HashMap result = new HashMap();
    connection = .......;
    Statement stmt=connection.createStatement();
    rs = stmt.executeQuery("Your query");
    int count=0;
    while(rs.next())
    count++;
    String question = rs.getString("colName");
    result.put(""+count,question); //( ""+count)>>>>>means converting int to String
    request.setAttribute("questions",result);
    ====================================================
    now in every JSP which is intended to display a question will have to get this result object..
    Lets assume we are about to display first question()....
    ===========================================
    //////// First get result map from request
    HashMap questions = (HashMap)request.getAttribute("questions");
    String count;
    count = request.getAttribute("count");
    if(count==null)
    count="1";
    String question = questions.get(count);
    count = new String(""+(Integer.parseInt(count).intValue()+1));
    ///Now do what you have to do with this questionresult
    questions.remove();
    request.setAttribute("count",count);////setting question no in request
    request.setAttribute("questions",questions);////setting rest of questions in request
    ===================================================
    hope this might be helpful........
    if there is any problem you can consult me anytime

  • Philisophical Question:  Tools for synchronizing JSPs, Java Beans and XML?

    This is a "best practices" question...
    The JSTL and JSF tags provide a lot of support for minimizing the amount of text that must be included in a JSP page. For example:
    <c:out value="${customer.firstName}"/>This snippet will find an object named "customer" in any of the JSP scopes, extract the value of the property named "firstName", and output it as part of the page.
    Here are my questions:
    (1) Is there a recommended method to communicate to the page designer what objects are in scope for a particular page, and what the properties of those objects are?
    (2) Is there any programmatic way to determine from the program's source code that an object with the specified name and of the expected type will be in scope at run time?
    I would love to have an IDE that would be able to help the page designer by providing a list of the objects that are expected to be in scope, along with the name of their properties. What conventions exist to make this possible?

    Maybe you like this, it's one of dozens of tools for Struts and in version 3.0
    http://www.scioworks.com/scioworks_camino.html
    hth,
    .V

  • A question about PreparedStatement and ORA-03115 error

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

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

  • Question about domain name/JSP, servlets

    I have a web host which publishes my pages, say www.zzz.com. I want to use JSP/Servlets on my machine which is using Apache Tomcat. Here's the problem, if I link a JSP/Servlet from www.zzz.com, the user will see my IP, i.e. 37.28.18.102/servlets/Calculations
    Is there a way where the people's browser's URL text field will always be www.zzz.com even if the page is located on my server?

    Try using Frameset where top frame is always www.xxx.com and child frame can be anywhere

  • Easy Question about PreparedStatement

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

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

  • Conceptual question regarding PreparedStatement

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

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

  • Architecture Question: Servlet, Bean, or JSP?

    I've found that alot of the time, the systems I'm trying to design can use all of these to accomplish the same task. What's a good indicator of whether or not I should be using one technology over another?
    For example, most recently, I designed an html form that is used to create registration html forms for clients. I can send the data in my form to another jsp page, a servlet, or a bean. ALL THREE can accept the date and use BufferedWriter to create and write to the registration form. Why would I want to use one over the other?
    Any help here would be greatly appreciated. I am seriously lacking in proper system design knowledge.

    The concept of JSPs was created to let Web designers design pages and developers to plug in the dynamic content. So essentially the JSPs are primarily for display on.
    Servlets are good for controlling the flow.
    Typically in any medium to large application, that's the distinction you'd want to have.
    So have a single controller servlet as a central entry point into your application. That's useful for certain validations such as login etc. Then the servlet performs whatever work is required and dispatches to a JSP to display the output of the work.

  • Forms + jsp quick question

    hi.
    i have a question regarding forms in jsp...
    i have a page on which a productid is passed to.
    when the page is opened, it displays the details of a product which the user has selected from previous pages (e.g. bids.jsp?productid=5)
    this page displays a form on which the user enters their userid and an amount to bid.
    <form method = "post" action ="bids.jsp?<%=productid %>+<%=userid %>+<%= amount %>">
    <p>User ID: <input type = "text" name = "userid" size = "5" value = ''></p>
    <p>Bid Amount: ?<input type = text" name = "amount" size = "4" value = ''></p>
    <p><input type = "submit" value = "Place Your Bid"></p>
    </FORM>
    now, when i click submit - it gives null for the userid and the amount (i.e. it doesn't seem to take them from the form). i tried .getSession, .getAttribute, .getParameter.... so i am obviously going wrong somewhere.
    i also want to execute a query (an insert query), when submit is pressed.
    it will be like this:
    insert into bids values ('<%=userid %>', '<%= productid %>' ...... etc)
    but obviously this won't work until i can TAKE that information from my form.
    any suggestions?
    thanks a million.

    i guess the best u can do is,
    Once u ran ur query and display, put the values in the hidden tag.
    like this,
    <input type="hidden" name="p_id" value="<%= product_id %>, do that for user and the amount thru all the > jsps u'd navigate.
    so in each of ur jsp file, u can get the values using request.getParameter();
    <%-- Execute query to display the chosen product --%>
    <%
    sql = ("select productid,................................ from product where productid = '"+ product_id +"'");
    rs = stmt.executeQuery(sql);
    %>u code works fine till this part right?
    HTML table goes here
    So, the table is displayed on the page. Below the table I want my form.
    A form goes here (my form, your form, another form ??).
    The form has a PLACE BID button.
    Then I want to grab the data from that form, and execute a query based upon the data taken from the form when the PALCE BID button is pressed.So here u'll be displaying the table with the details of the product. since ur query criterion is a product_id, u'll get only a single row of info. So in the jsp page where u display these tables, have hidden tags inside ur form as I said.

  • Beginner JSP / Forms question

    Hello,
    I'm just starting with jsps and I've got a pretty simple question. In my jsp I generate a form with two fields: age and weight. I'm wondering what the best method is for handling the users response. Two specific questions: (1) I'm currently handling the response in the same jsp which generates the form. Is this bad, uh, form? (2) To differentiate between the 'initial' request and the request resulting from the users form submission I'm arbitrarily checking whether the value of the 'age' parameter is null. Is there a better way to do that? Thanks in advance for any thoughts on these issues.
    -exits

    Yeah, that is fine for early JSPs (on both questions).
    A couple of thoughts:
    1) What if the user submits a weight but not an age? You should probably check if either of the two inputs are null.
    2) This design is fine for smaller applications (it is called the Model 1 application design). For more complex applications, using Model 2 (Model - View - Controller or MVC) pattern is much better.
    Basically you use a combination of Servlets and JSPs. One servlet is the target of all your links and forms - this is the Controller. Based on parameters and other conditions, the controller determines where the page should go next, and accesses the business logic (other classes that get/store data or calculates results. These other classes are the Model) , and passes this information to the the JSP needed to display that information (the View).
    This helps JSPs stay small and manageable, since adding to much logic in a JSP means writing scriptlets, which become tough to maintain later on. It takes more work up front, but for larger apps and over longer periods of time (when it becomes time to update the look, or fix bugs) it makes a lot of sense.

  • Apostrophes are replaced by question marks in output string?

    Hi Guys
    I think this is an encoding problem but I cannot find it in the forum archives. My apostrophes are being replaced by question marks on my jsp output?
    Any idea why and how to get them back to apostrophes
    Cheers, ADC

    Guys, the 3rd party product has no trouble at all
    showing the apostrophes from the self-same database
    that I get question marks from.
    This MUST be an encoding issue, so anyone that knows
    about encoding and changing it please could you
    suggest something. You can take for granted that one
    way or another the character in the database IS an
    apostrophe as verified by viewing it via the 3rd party
    product we have.You said...
    In the SQL database view they come out as squares
    Were you referring to the normal applications that are available for viewing data for the database (like SQL*Plus or Enterprise Manager?)
    If yes, then if it was me then I would presume it was not an apostrophe and that the third party tool was mapping the real character to an apostrophe. A 'square' indicates an unusual character in viewers.
    Are you using EBCDIC? Unless EBCDIC is involved apostrophe has the same value in most if not all character sets because ANSI forms the lower range for most character sets. I know for example that Korean, Japanese and Chinese character sets use ANSI, as does unicode (with padded zeros for the wider ranges.)

  • How to deploy Web Layout Report which is embedded in a JSP in 10.1.3 ??

    Hi there,
    we like to create a JSP report with web and paper layout. The paper layout is for pdf and the web layout to fit the page in the whole application. The whole application will be a JSF application running on 10.1.3. The reason why we like to use Reports is the capability of creating pdf and because of a couple of charts we have to build - using chart builder.
    Now the question is how the JSP has to be deployed because the Reports engine is running on another 10.1.2 server. So the JSP itself has to run on 10.1.3 but the Report has to run on 10.1.2 - is it possible, a problem or is it just easy?
    Regards, Peter

    Hi there,
    we like to create a JSP report with web and paper layout. The paper layout is for pdf and the web layout to fit the page in the whole application. The whole application will be a JSF application running on 10.1.3. The reason why we like to use Reports is the capability of creating pdf and because of a couple of charts we have to build - using chart builder.
    Now the question is how the JSP has to be deployed because the Reports engine is running on another 10.1.2 server. So the JSP itself has to run on 10.1.3 but the Report has to run on 10.1.2 - is it possible, a problem or is it just easy?
    Regards, Peter

  • Converting JSP to servlet

    Hi,
    Can anyone show me how to convert my jsp to servlet. Then, from servlet to classes. Thanks.
    cheers,

    well, jsp pages are converted at run-time to servlets, e.g. if you are using tomcat as jsp engine, you will find the servlet java files somewhere under $TOMCAT_HOME/work/localhost. you can compile these java files to class files.
    PS: There is a forum in here for JSP, and I would recommend that you post your questions there in the JSP forum (this one is about databases)

  • Using PreparedStatement and the Oracle Error ORA-1000

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

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

Maybe you are looking for

  • Report Painter Quantity & Dollars

    Dear All, Could please someone help with the following: Create a report in GRR2 which shows in the same column Dollars ans Quantity e.g Sales      $10,000          (dollars from Cost element/Cost center) Qty Sold         10          (quantity as Stat

  • Not displaying new messages

    Before when I checked my email, the number of new messages would be displayed on the email icon on my screen.  Now it doesnt show up, even tho there are new, unopen messages in my mailbox.  I've tried powering off & Hard reset.  Anyone else had this

  • Why Do I Get An UAC Prompt When I Start Task Manager From The Desktop?

    Windows 8 Pro X64 In Windows 7 Ultimate x64 if I start Task Manager by right clicking on the taskbar and selecting it it starts without any UAC prompt running in my security context.  It is only if I click on show processes from all users that I get

  • Do you know about the way for saving any monitoring context to file

    I want to save text file(s) with any log or info. about the status of managed target(s). But I could not find the answer. Please, let me know... Is this enable or not? If enable... How could I do that? Regards...

  • Help...i'm stuck at BLUE SCREEN

    hai all... actually i'm newbie with mac comp... so here is my problems..the problems comes after finishing installing the paragon ntfs software,which is required to restart.. so I restart my macbook and the problems coming..the log on screen features