JSP Strings, Ints converting

I'm sure this sort of thing has been asked but i cant find it in the forums.... I'm trying to read in a string from a form and then convert it to an int so that i can use it in a select statement so i can compare it to a field declared as "Number" in the Access Database.
String sess = request.getParameter("num"); //num comes from form
int eventNum = Integer.parseInt(sess);
//connected ot the database
String query = "SELECT * FROM EVENT WHERE event_id = 'eventNum' ";
ResultSet result = stmt.executeQuery(query);
//event_id is a number in the database
Its saying "Data type mismatch in criteria expression"
Thanking you in advance,
Brian

Since you are building a string as query, you don't need to convert it
String sess = request.getParameter("num"); //num
String query = "SELECT * FROM EVENT WHERE event_id ='eventNum' ";
ResultSet result = stmt.executeQuery(query);This error "Data type mismatch in criteria" comes from event_id = 'num'
event_id is numeric, so it should not contain quotes in the sql statement
this will do it:
String query = "SELECT * FROM EVENT WHERE event_id =" + sess

Similar Messages

  • Passing asp form data to a .jsp string

    Hello and thanks in advance for any help.
    I would like to pass form information that comes from a standard form into a URL string as follows:
    "http://ui.constantcontact.com/roving/wdk/API_AddSiteVisitor.jsp?loginName=benefitevents&loginPassword=connoisseur&ea=[email protected]&ic=test&first_name=Joe&last_name=smith"
    I would then like to pass that string forward to its final destination.
    Some more info.
    Form data is collected on "register.asp" and then passed to "register1.asp" using form method="post" action="register1.asp".
    On register1.asp the form info is processed and delivered to the SQL database.
    I am only a beginner with the code (it was done by a programmer who is mostly absent when needed now).
    So, I need to know as much of the following as you can help with (in descending priority):
    1. How to pass the .jsp string forward assuming the proper variables have been passed in the asp code.
    2. Where should this command live, in register.asp or register1.asp?
    3. How to correctly insert the variables in the URL string from form (correct syntax using asp).
    As may be obvious this is for one registrant at a time. The object is deliver the registration information to my SQL database and, at the same time, pass some info to a Constant Contact list. This allows me to integrate Constant Contact into my services to clients seamlessly.
    Thank you, hope this was not too much info!
    Jim

    Javascript is not the same as Java.
    There are JS related forums at webdeveloper.com. But I would rethink about the JS approach. It should also be able with ASP and I would prefer that.

  • HELP ON java.lang.String,int

    Im very new to java.please help!!!
    im having this error after compiling this:-
    public boolean setBookname(String newName)
              if (newName >0)
                   BookName = newName;
              else
                   return false;
    A:\Book.java:30: operator > cannot be applied to java.lang.String,int
              if (newName >0)
    ^
    1 error
    Process completed.
    thank u!

    The OP should read about IllegalArgumentException.Indeed. And a few other things as well...
    http://java.sun.com/docs/books/tutorial/
    http://java.sun.com/learning/new2java/index.html
    http://javaalmanac.com
    http://www.jguru.com
    http://www.javaranch.com
    Bruce Eckel's Thinking in Java
    Joshua Bloch's Effective Java
    Bert Bates and Kathy Sierra's Head First Java

  • String - int

    i want to convert a string var into int var?
    how is that possible in jsp?
    thank you!

    int intvar = Integer.parseInt(StringVar);

  • Newbie to JSP, Need to convert some ASP code to work for JSP

    Can I get some aid in converting the following ASP code to work using JSP. I have never used JSP before but I now need to because of a recent server change.
    <%
    DIM URL
    URL = LCase(Request.ServerVariables("URL"))
    if InStr(URL, "/about/") then
    %>
    <p>About Test</p>
    <% elseif InStr(URL, "/menu/") then %>
    <p>Menu Test</p>
    <% elseif InStr(URL, "/contact/") then %>
    <p>Contact Test</p>
    <% else %>
    <p>Test</p>
    <% End if %>Thanks in advance
    Ned

    Can I get some aid in converting the following ASP
    code to work using JSP. I have never used JSP before
    but I now need to because of a recent server change.
    <%
    DIM URL
    URL = LCase(Request.ServerVariables("URL"))
    if InStr(URL, "/about/") then
    %>
    <p>About Test</p>
    <% elseif InStr(URL, "/menu/") then %>
    <p>Menu Test</p>
    <% elseif InStr(URL, "/contact/") then %>
    <p>Contact Test</p>
    <% else %>
    <p>Test</p>
    <% End if %>Thanks in advance
    Ned<%
    String sURL = request.getRequestURL();
    if (sURL.indexOf("//about//") > 1) {
    %>
    <p>About Test</p>
    <%
    } else if (sURL.indexOf("//menu//") > 1) {
    %>
    <p>Menu Test</p>
    <%
    } else if ......
    %>
    I wont do the other cases. Im sure you can figure it out. Hope it helps!

  • JSP Servlet and convert the result set of an SQL Query To XML file

    Hi all
    I have a problem to export my SQL query is resulty into an XML file I had fixed my servlet and JSP so that i can display all the records into my database and that the goal .Now I want to get the result set into JSP so that i can create an XML file from that result set from the jsp code.
    thisis my servlet which will call the jsp page and the jsp just behind it.
    //this is the servlet
    import java.io.*;
    import java.lang.reflect.Array;
    import java.sql.*;
    import java.util.ArrayList;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.naming.*;
    import javax.sql.*;
    public *class *Campaign *extends *HttpServlet
    *private* *final* *static* Logger +log+ = Logger.+getLogger+(Campaign.*class*.getName());
    *private* *final* *static* String +DATASOURCE_NAME+ = "jdbc/SampleDB";
    *private* DataSource _dataSource;
    *public* *void* setDataSource(DataSource dataSource)
    _dataSource = dataSource;
    *public* DataSource getDataSource()
    *return* _dataSource;
    *public* *void* init()
    *throws* ServletException
    *if* (_dataSource == *null*) {
    *try* {
    Context env = (Context) *new* InitialContext().lookup("java:comp/env");
    _dataSource = (DataSource) env.lookup(+DATASOURCE_NAME+);
    *if* (_dataSource == *null*)
    *throw* *new* ServletException("`" + +DATASOURCE_NAME+ + "' is an unknown DataSource");
    } *catch* (NamingException e) {
    *throw* *new* ServletException(e);
    protected *void *doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException
    Connection conn = *null*;
    *try* {
    conn = getDataSource().getConnection();
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("select post_id,comments,postname from app.posts");
    // out.println("Le r&eacute;sultat :<br>");
    ArrayList <String> Lescomments= *new* ArrayList<String>();
    ArrayList <String> Lesidentifiant = *new* ArrayList<String>();
    ArrayList <String> Lesnoms = *new* ArrayList <String>();
    *while* (rs.next()) {
    Lescomments.add(rs.getString("comments"));
    request.setAttribute("comments",Lescomments);
    Lesidentifiant.add(rs.getString("post_id"));
    request.setAttribute("id",Lesidentifiant);
    Lesnoms.add(rs.getString("postname"));
    request.setAttribute("nom",Lesnoms);
    rs.close();
    stmt.close();
    *catch* (SQLException e) {
    *finally* {
    *try* {
    *if* (conn != *null*)
    conn.close();
    *catch* (SQLException e) {
    // les param&egrave;tres sont corrects - on envoie la page r&eacute;ponse
    getServletContext().getRequestDispatcher("/Campaign.jsp").forward(request,response);
    }///end of servlet
    }///this is the jsp page called
    <%@ page import="java.util.ArrayList" %>
    <%
    // on r&eacute;cup&egrave;re les donn&eacute;es
    ArrayList nom=(ArrayList)request.getAttribute("nom");
    ArrayList id=(ArrayList)request.getAttribute("id");
    ArrayList comments=(ArrayList) request.getAttribute("comments");
    %>
    <html>
    <head>
    <title></title>
    </head>
    <body>
    Liste des campagnes here i will create the xml file the problem is to display all rows
    <hr>
    <table>
    <tr>
    </tr>
    <tr>
    <td>Comment</td>
    <td>
    <%
    for( int i=0;i<comments.size();i++){
    out.print("<li>" + (String) comments.get(i) + "</li>\n");
    }//for
    %>
    </tr>
    <tr>
    <td>nom</td>
    <td>
    <%
    for( int i=0;i<nom.size();i++){
    out.print("<li>" + (String) nom.get(i) + "</li>\n");
    }//for
    %>
    </tr>
    <tr>
    <td>id</td>
    <td>
    <%
    for( int i=0;i<id.size();i++){
    out.print("<li>" + (String) id.get(i) + "</li>\n");
    }//for
    %>
    </tr>
    </table>
    </body>
    </html>
    This is how i used to create an XML file in a JSP page only without JSP/SERVLET concept:
    <%@ page import="java.sql.*" %>
    <%@ page import="java.io.*" %>
    <%
    // Identify a carriage return character for each output line
    int iLf = 10;
    char cLf = (*char*)iLf;
    // Create a new empty binary file, which will content XML output
    File outputFile = *new* File("C:\\Users\\user\\workspace1\\demo\\WebContent\\YourFileName.xml");
    //outputFile.createNewFile();
    FileWriter outfile = *new* FileWriter(outputFile);
    // the header for XML file
    outfile.write("<?xml version='1.0' encoding='ISO-8859-1'?>"+cLf);
    try {
    // Define connection string and make a connection to database
    Connection conn = DriverManager.getConnection("jdbc:derby://localhost:1527/SAMPLE","app","app");
    Statement stat = conn.createStatement();
    // Create a recordset
    ResultSet rset = stat.executeQuery("Select * From posts");
    // Expecting at least one record
    *if*( !rset.next() ) {
    *throw* *new* IllegalArgumentException("No data found for the posts table");
    outfile.write("<Table>"+cLf);
    // Parse our recordset
    // Parse our recordset
    *while*(rset.next()) {
    outfile.write("<posts>"+cLf);
    outfile.write("<postname>" + rset.getString("postname") +"</postname>"+cLf);
    outfile.write("<comments>" + rset.getString("comments") +"</comments>"+cLf);
    outfile.write("</posts>"+cLf);
    outfile.write("</Table>"+cLf);
    // Everything must be closed
    rset.close();
    stat.close();
    conn.close();
    outfile.close();
    catch( Exception er ) {
    %>

    Please state your problem that you are having more clearly so we can help.
    I looked at your code I here are a few things you might consider:
    It looks like you are putting freely typed-in comments from end-users into an xml document.
    The problem with this is that the user may enter characters in his text that have special meaning
    to xml and will have to be escaped correctly. Some of these characters are less than character, greater than character and ampersand character.
    You may also have a similiar problem displaying them on your JSP page since there may be special characters that JSP has.
    You will have to read up on how to deal with these special characters (I dont remember what the rules are). I seem to recall
    if you use CDATA in your xml, you dont have to deal with those characters (I may be wrong).
    When you finish writing your code, test it by entering all keyboard characters to make sure they are processed, stored in the database,
    and re-displayed correctly.
    Also, it looks like you are putting business logic in your JSP page (creating an xml file).
    The JSP page is for displaying data ONLY and submitting back to a servlet. Put all your business logic in the servlet. Putting business logic in JSP is considered bad coding and will cause you many hours of headache trying to debug it. Also note: java scriptlets in a JSP page are only run when the JSP page is compiled into a servlet by java. It does not run after its compiled and therefore you cant call java functions after the JSP page is displayed to the client.

  • String & Int in Bean

    Hi,
    i'm building a webapp to simply allow the user to enter his or her details which will be submitted with all the details stored in the bean. When deciding to either make properties such as age or telephone number as string or int in a bean, i read somewhere that it is a rule of phumb to set these properties as Strings as they are easier to validate. If that is the case, if i create a property of String age with it's corresponding getter and setter method i.e
    public void setAge(String n) {
        age = n ;
    public String getAge()
       return age;
    doing something like the above would not convert the value into an int which is what i would like to do. Therefore, i was thinking of doing the following in my bean class:
    package beans ;
    public class Person
    private int age ;
    // Constructor
    public Person() {
        age = 0 ;
    public void setAge(int n) {
        age = n ;
      public void setAge(String s) {
        try {
          age = Integer.parseInt(s) ;
        catch (NumberFormatException e) {}
      public int getAge() {
        return age ;
      }doing the above would i think be more convenient. Would that be the better way do you think?
    cheers

    BigDaddyLoveHandles wrote:
    raychen wrote:
    There's nothing wrong with what you are doing, however.I disagree. First that code doesn't belong in a bean. An then it has to be dupilcated across every bean and every "int" property. Plus I disagree with the way it swallows formatting errors.BigXXXXXwhatever...... what do you mean by that code does not belong in the bean. I've seen my example duplicated in many exampls and in books. I'm not to concerned if it has to be duplicated in every bean and int, it's not what i was asking.
    In terms of the fomatting errors, what errors? Do i need to correct something?
    Thanks for your input raychen.
    Edited by: nvidia1 on Jan 6, 2009 12:19 AM

  • Empty Strings are converted to NULLs

    We are developing a Java application intended to work with multiple databases. We want to store empty strings but oracle converts this to NULL values. Is there a way to tell the Oracle Database not to convert the empty string to NULL and to store it as an empty string?
    Thanks
    Joaquim Franco <[email protected]>
    GEDI, SA

    Our project started with a MySQL database and the code is full of built queries like "Select Field from table where field = var" where var can be an empty string. It would be easier for us to turn a switch in the database then to look for every query in the application and add code to test is var is empty a change the query to "Select Field from table where field is NULL".
    Best Regards
    Joaquim Franco
    &gt; It is a quirk of Oracle that it regards empty strings
    &gt; and NULLs as being the same thing. This behaviour
    &gt; has been built into the database forever. Oracle
    &gt; keep threatening to change but I suspect they are
    &gt; scared of the impact, not least on their own code.
    &gt; As Oracle increasingly embrace Java they may decide
    &gt; to revisit this - I don't know whether the behaviour
    &gt; is changed in 10G.
    &gt;
    &gt; What sort of problems does it cause you?
    &gt;
    &gt; Cheers, APC

  • JTextField(Document, string, int)

    Dear friends,
    Could you just tell me how can I fix the size of the JTextField,
    such as just accept the maximum number of digits or characters in JTextField...
    I cant create the Document....
    Could anyone give me a tips?

    I found the best way to do this is to subclass PlainDocument as follows:
    public class MyTextDoc extends PlainDocument
        int maxCharacters;
        public MyTextDoc(int maxChars) {
            maxCharacters = maxChars;
        public void insertString( int offs, String str,  AttributeSet a )
                    throws BadLocationException {
            if( (getLength() + str.length()) <= maxCharacters)
                super.insertString(offs, str, a);
            else
                Toolkit.getDefaultToolkit().beep();
    }I then use this document in the constructor for all my JTextFields.
    I'm not sure what you mean by "I cant create the Document...."
    Cheers
    Gary

  • Content in Jsp to be converted to Word Doc

    I have .jsp page. with some generated content. In that page, there is an option Convert to Word DOC PAGE. When the link is clicked , the content in the JSP page has to be converted to a Word Doc. How to do?

    <%@ page language="java" %>
    <%@ page import="java.util.*" %>
    <%@ page import = "java.io.*" %>
    <HTML>
    <HEAD>
    <script language="JavaScript">
    var fso = new ActiveXObject('Scripting.FileSystemObject');
    var wdApp = new ActiveXObject("Word.Application");
    function readFromFile(fileName)
         if (fileName == "C:\\Award_Ltr.TXT")
    var fs = fso.OpenTextFile(fileName);
    var result = fs.ReadAll();
    return result;
    function readFromWord()
    alert("PLEASE SAVE THE FILE AS C:\PPY Letter for Annuities to Retirees and Alternate Payees wi_temp.doc");
    var pause = 0;
    var wdDialogFileOpen = 80;
    var wdApp = new ActiveXObject("Word.Application");
    var dialog = wdApp.Dialogs(wdDialogFileOpen);
    var button = dialog.Show(pause);
    </SCRIPT>
    </HEAD>
    <BODY>
    <FORM NAME="formName">
    <INPUT TYPE="file" NAME="fileName">
    <INPUT TYPE="button" VALUE="show"
    ONCLICK="this.form.fileContent.value = readFromFile(this.form.fileName.value)">
    <BR>
    <TEXTAREA NAME="fileContent" ROWS="20" COLS="90" WRAP="off"></TEXTAREA>
    <BR>
    <INPUT TYPE="button" VALUE="SaveExtract" >
    <BR>
    <INPUT TYPE="button" VALUE="Modify Template" onClick = "readFromWord()">
    </FORM>
    </BODY>
    </HTML>

  • String trace |  Convert to URL html format

    Hi,
    I have an html page with a <form> tag that calls a servlet.
    The servlet insert user's input into a DataBase.
    Another jsp page pulls out this record from the DataBase.
    If user inputs a URL link such as http://java.sun.com I want it to be displayed as a clickable URL. So, I need to parse user's input and if URL found insert it into a database in valid html formaty such as
    http://java.sun.com
    How can I parse user's input and find out that it contains a URL?
    I bet I have to use RE.
    Is there a good code example out there?
    Thank you.

    I bet I can trace it and check
    loop over the string
    if charAt(i) is h
    next step if charAt(i) t
    next step if charAt(i) t
    next step if charAt(i) p
    next step if charAt(i) :
    next step if charAt(i) /
    next step if charAt(i) /
    next step if charAt(i) w
    next step if charAt(i) w
    next step if charAt(i) w
    next step if charAt(i) .
    OR
    next step if charAt(i) w
    next step if charAt(i) w
    next step if charAt(i) w
    next step if charAt(i) .
    than build up valid html string
    but would it be a good solution?
    Thanks.

  • Diff. bet. JSP String ( %! String) and Java String.

    Hi all,
    Think this is one of the basic Questions.
    I want to know the basic diff. between <%!String a=10; %> and <%String a=10; %> programmatically,
    with an example.
    Bye
    Sreedhar

    <%! ... %> are called jsp declarations, and are inserted into the generated servlet class.
    <% ... %> are called jsp scriptlets, and are inserted into the _jspService method.
    For example, the following jsp :
    <%! String a = "10"; %>
    <%!
      public void helloWorld() {
         System.out.println("Hello world");
    %>
    <% String b = "10"; %>Might be translated to the following servlet code :
    String a = "10";
    public void helloWorld() {
       System.out.println("Hello world");
    public void _jspService(...) ... {
      String b = "10";
    }

  • Error  executeUpdate(String,int)

    i try execute follow source and obtain error:
    Exception in thread "main" java.lang.NoSuchMethodError
    at ProbaInsertId.getKey(ProbaInsertId.java:54)
    at ProbaInsertId.main(ProbaInsertId.java:19)
    import java.util.*;
    import java.io.*;
    import java.sql.*;
    public class ProbaInsertId
    public static void main(String args[])
         getKey();
    public static void getKey(){
         int key = 0;
              String nume="zzz";
              String prenume="fff";
              try{
                   Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
              catch(Exception e) {
                   e.printStackTrace();     
                   System.out.println("Eroare incarcare driver!\n" + e);
              Connection conn = null;
              try{
              conn = DriverManager.getConnection( "jdbc:microsoft:sqlserver://mother:1433;DatabaseName=db", "mihai", "mihai");
    String sqlQueryInsert = "INSERT INTO proba (nume, prenume) " +
                             "VALUES(nume, prenume)";
    Statement sqlStatementInsert = conn.createStatement();
                   sqlStatementInsert.executeUpdate(sqlQueryInsert,sqlStatementInsert.RETURN_GENERATED_KEYS);
    ResultSet rs = sqlStatementInsert.getGeneratedKeys();
    if( rs.next() ){
         key = rs.getInt(1);
                        System.out.println(key);
                        sqlStatementInsert.close();
                        conn.close();
              catch(Exception e) {
                   e.printStackTrace();     
                   System.out.println("Eroare select 2!\n" + e);

    Sounds like that JDBC driver doesn't support getting auto-generated keys. - MOD

  • Jsp string of a datetime value error

    Hi all, I got this problem in one jsp recently, sql0181N String representation of a datetime value is out of range. However, this error just occur in recently, there is no such error before and the page can successfully loaded with proper function. And I didn't change the code of the related page so far, why leads to such problem. The page is just for displaying several years data, show the data week by week, that's why need the string of datetime value. And the page can successfully show all data for several months, so I would like to know why it suddenly has such error? Anyone can offer me a helping hand? Really thanks a lot.

    This is caused by an invalid date, which you may know, perhaps you changed the date format somewhere? or the locale on the page?
    so instead of 12/31/2008 being new years eve you might be trying 31/12/2008 which is invalid?
    just a thought.

  • Send to pushView string to convert to viewClass

    i have problem with convert string to Class i try getDefinitionByName() >>> get undefined Varabile
    how can i do it
    function gotoView (currView:String):void{
    navigator.pushView(currView as Class );// error
    please help me to solve that

    String[] splitString = str.split(",");

Maybe you are looking for

  • Batch date in iphoto

    I have used an Automator script to batch time and date in iPhoto when the usual methodology within iPhoto's batching did not work adequately. Can you help me with an Automator script and teach me how to install it for iPhoto to recognize it within iP

  • Parameter in Crystal Report 8.8

    Dear Experts, I'm creating a stored procedures with few parameters. When I preview the report using Crystal Report 8.8, i can set parameters to NULL and the stored procedures will know to capture all information without any filtering. But when i Prev

  • Move (or access) Aperture library to new mac from other mac (over the air)

    I had Aperture 1.5.6 on my iMac. I upgraded to snow leopard and now Aperture will not work. Apple says the old version does not work with the new. Now I cant get to any of my pics. So I loaded my copy of Aperture on my Macbook air which still has leo

  • When i try to install Photoshop Elements 10 why does it keep telling me to insert disk

    I purchased a Wacom Bamboo Create and it came with a software package which included Photoshop Elements 10 but when I try to install it, it accepts my serial number but won't let me complete the process. It keeps telling me i need to "insert Photosho

  • Blank album art

    I know this must be asked alot of times, but i wanted to create my own thread so i can ask more question. I experience blank album art in my ipod. how can i fix this?