JSP-JDBC Help

Hi everone,
Can you please let me know how can I insert "-" or "+" into my sql Database. for example the code bellow, imagin c =10, taken from the user, I want to insert C as "-10" or "+10" into databse
String str= "insert into table values ('"+a+"', '"+b +"','"+-c+"')"; //c=-10
String str= "insert into table values ('"+a+"', '"+b +"','"+ +c+"')";//c= +10
[/code
Thank you]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

Here is a basic overview of PreparedStatement. I will assume at this point you've already created your Connection, and named it "con".
Let's also assume that you've acquired an int value from somewhere and named it "employeeId".
NOTE: This is untested code! I've left out extraneous details, such as storing the results in a ResultSet, and also any try/catch statements.
final String MY_SELECT_STATEMENT = "SELECT * FROM EMPLOYEES WHERE empId = ?";
PreparedStatement prepState = con.prepareStatement(MY_SELECT_STATEMENT);
prepState.setInt(1, employeeId);
prepState.execute();See the question mark(?) in the query String called MY_SELECT_STATEMENT? You can put a "?" anywhere you want to put in a variable.
The next line to note is the prepState.setInt(1, employeeId) line. The "1" refers to the "?" in the query. If there was another "?", then it would be "2".
The prepState object has other methods, such as setString, etc. This should correspond to the type of data that your setting.
Not only is this cleaner and a more accepted way of running queries, but there are also some security upsides to this, as it makes SQL injection harder (if not impossible) for hackers.
That should get you started. Definitely read the link in the previous posters msg.
Regards.

Similar Messages

  • Can't find "Delegate Class Name" for JDBC Helper Service

    Hi,
    I downloaded WLServer 6.1 with sp1 and WLPortal 4.0, installed them on Solaris 7 using default DB cloudscape -- everything was fine. Now, I'm trying to configure database to Oracle 8.1.7.
    In "Configure the JDBC Helper Service" section of document "Configuring WebLogic Portal for Oracle Databases" (http://e-docs.bea.com/wlp/docs40/deploygd/oraclnew.htm), step 2 requires to enter value of "com.bea.p13n.util.jdbc.internal.OracleJDriverJdbcHelperDelegate" to "Delegate Class Name". But, I can't find this "Delegate Class Name" variable. The available varialbles on the Configuration tab on my screen are: Maximum Number of Retries, Maximum Wait Time (milliseconds), Use CLOBs for Read?, Use CLOBs for Write?. And the Configuration tab is the only available tag for JDBC Helper Service. Did I download a different version from other people? I downloaded it within 3 months.
    Can anyone help?
    Thanks in advance,
    Jane

    Thanks Steve.
    I had my own jndi.properties file that's why it was working with ejb bean I created in the AM and not with the sdo web service.
    I didn't know I had to add the jndi properties to the connection.xml maybe you can update the documentation.
    <?xml version = '1.0' encoding = 'UTF-8'?>
    <ns2:References xmlns:ns2="http://xmlns.oracle.com/adf/jndi">
    <Reference className="oracle.jbo.client.svc.Service"
    name="{/test/model/common/}DepartmentModuleService">
    <Factory className="oracle.jbo.client.svc.ServiceFactory"/>
    <RefAddresses>
    <StringRefAddr addrType="serviceInterfaceName">
    <Contents>test.model.common.serviceinterface.DepartmentModuleService</Contents>
    </StringRefAddr>
    <StringRefAddr addrType="serviceEndpointProvider">
    <Contents>ADFBC</Contents>
    </StringRefAddr>
    <StringRefAddr addrType="jndiName">
    <Contents>test.model.common.DepartmentModuleServiceBean</Contents>
    </StringRefAddr>
    <StringRefAddr addrType="serviceSchemaName">
    <Contents>DepartmentModuleService.xsd</Contents>
    </StringRefAddr>
    <StringRefAddr addrType="serviceSchemaLocation">
    <Contents>test/model/common/serviceinterface/</Contents>
    </StringRefAddr>
    <StringRefAddr addrType="jndiFactoryInitial">
    <Contents>oracle.j2ee.rmi.RMIInitialContextFactory</Contents>
    </StringRefAddr>
    <StringRefAddr addrType="jndiProviderURL">
    <Contents>ormi://localhost:23791/SvcInterfaceDeploy_MiddleTier</Contents>
    </StringRefAddr>
    <StringRefAddr addrType="jndiSecurityPrincipal">
    <Contents>fmwadmin</Contents>
    </StringRefAddr>
    <StringRefAddr addrType="jndiSecurityCredentials">
    <Contents>welcome</Contents>
    </StringRefAddr>
    <StringRefAddr addrType="serviceSchemaName">
    <Contents>HRAppService.xsd</Contents>
    </StringRefAddr>
    </RefAddresses>
    </Reference>
    </ns2:References>
    thanks edwin

  • Cannot access VARCHAR2s on Oracle 9i using JSP/JDBC

    After upgrading from Oracle 8.1.7 to Oracle 9, I get an
    exception when using JSP/JDBC to read data from columns
    containing VARCHAR2s. I can successfully read columns
    containing BLOBs, CLOBs, NUMBERs, and RAWs.
    I still can select VARCHAR2 columns by using SQL*Plus so the
    problem is with JDBC and not the database.
    I get the following exception message:
    java.sql.SQLException: ORA-00600: internal error code,
    arguments: [ttcgcshnd-1], [0], [], [], [], [], [], []
    The following code that worked on Oracle 8 fails to execute
    properly on Oracle 9:
    OracleResultSet rs = null;
    String sql = "select name from users where id > 100";
    rs = (OracleResultSet)s.executeQuery(sql);
    I'm using Windows 2000, Tomcat 3.2.2, Java 1.3, and the latest
    version of OracleJSP.
    Has anyone run into this problem?
    I've also entered this same query on the Java-SQLJ/JDBC
    discussion fourm.

    I4ve installed Oracle 9i on RedHat 7.2.
    We develop with WebObjects and JBuilder.
    When i try to connect to the database via the EOModeller (JDBC) i got the same error:
    Stack Trace:
    JDBCAdaptorException: ORA-00600: Interner Fehlercode, Argumente: [ttcgcshnd-1], [0], [], [], [], [], [], []
    Then, i started creating and droping tables in the 9i Database >> it works fine.
    Can someone give an solution for this problem??

  • Best way to create, modify, XML with JSP ?  HELP

    Hi friends,
    As i am new to XML,
    I know there are two APIs used for XML processing, i want to know as a begineer level, which API
    is easy and good to implement XML with JSP.
    1) SAX
    2) DOM
    i want to make a log file in XML, so on web page it will be displayed on HTML form through XSL.
    Since there is good tutorial on http://www.w3schools.com/dom
    but i think its HTML dom
    I want XML procession through JAVA CODE , what should i use ? and give some good tutorials on XML DOM
    that is used with JAVA / JSP.
    HELP.
    Edited by: Ghanshyam on Sep 19, 2007 3:24 PM

    Well what i think is you gonna checkout with your requirements before implementing any of the popular XML parsing mechnisms.
    If you are intrested in faster processing @sacrifising a gud amount of your Memory,DOM is the one which you are looking for.
    If you are instrested in Managing your memory and but if you are ok with sacrifising speed SAX is the best solution.it works on what is called a push technology.
    and if you think either way you might have to look towards a pull parser which is StAX (Streaming API for XML Parsing)
    it'd be a gr8 idea if you can go through the below article which explians about each of the parsing mechanisms
    http://www.stylusstudio.com/xml/parser.html#*
    coming back to helpful resources as far java is concern checkout the below link which might be of some help.
    and the main thing is that all of these parser there is a defined specification you might find implementations of different vendors on this.
    eg:Sun Provides one with JDK itself,same as IBM provides one,oracle does the same & so on...
    your first task would be to focus on one such implementation which can cater your requirements.
    DOM:*
    Basic Parsing Objects / Interfaces Involved while DOM parsing:
    http://www.w3.org/TR/DOM-Level-2-Core/java-binding.html
    Breif Overview & few important API details:
    http://www.developerlife.com/domintro/default.htm
    Simple Example:
    http://www.brics.dk/~amoeller/XML/programming/domexample.html
    Others:
    http://www.roseindia.net/xml/dom/
    http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JAXPDOM.html#wp79994
    http://java.sun.com/webservices/jaxp/dist/1.1/docs/tutorial/dom/1_read.html
    SAX:*
    http://www.javacommerce.com/displaypage.jsp?name=saxparser1.sql&id=18232
    http://java.sun.com/webservices/jaxp/dist/1.1/docs/tutorial/sax/index.htm
    http://java.sun.com/developer/Books/xmljava/ch03.pdf
    http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JAXPSAX.html#wp69937
    http://www.onjava.com/pub/a/onjava/excerpt/java_xslt_ch5/index.html?page=6
    StAX:*
    http://java.sun.com/webservices/docs/1.6/tutorial/doc/SJSXP2.html
    http://javaboutique.internet.com/tutorials/stax/
    http://today.java.net/pub/a/today/2006/07/20/introduction-to-stax.html
    Hope this might be of some help :)
    REGARDS,
    RaHuL
    http://weblogs.java.net/blog/spericas/archive/2006/04/sun_stax_parser.html

  • Servlet/jsp/jdbc best approach

    Hello guys
    Which is the best approach when developing servlet/jsp/jdbc? I will take an
    example:
    I have index-page, page2 and page 3.
    When the user writes www.mydomain.com then the page index.jsp checks if the
    user is coming from the servlet, like this:
    <%
    if(request.getAttribute("getPageTitle")==null){
    %>
    <jsp:forward page="/Index" />
    <%
    else{
    %>
    <%@ include file="/include/header.jsp" %>
    content for index.jsp
    <%@ include file="/include/footer.jsp" %>
    <%
    %>
    On the other hand, the Index class has this init()
    public void init(ServletConfig config) throws ServletException {
    super.init(config);
    con = DatabaseConf.getConnection();
    DatabaseConf is a class that handles all the operations related to the
    database.
    Index.class has also the doGet-method like this:
    request.setAttribute ("getPageTitle", "AnyTilte");
    getServletConfig().getServletContext().getRequestDispatcher("/index.jsp").forward(request,
    response);
    Does it looks ok so long?
    Now, I have other pages, page2 and page3 (in fact I have mych more than just
    these, but this is only an example)
    pages.jsp works as index.jsp. It makes a check
    <%
    if(request.getAttribute("getPageTitle")==null){
    %>
    if not satisfied than it redirect to
    <jsp:forward page="/Page2" />
    My concern, however, is about databasemanagement. Even the Page.class has an
    init-method that looks exactly like the one in Index.class, e.g.
    public void init(ServletConfig config) throws ServletException {
    super.init(config);
    con = DatabaseConf.getConnection();
    In conclusion, Im starting jdbc-connection for every class-file that
    initiates. Is this a good approach? What I would like is a solution to
    initiate the database only one time, when the server starts. Not everytime,
    the first time a specially class-file will be called. I know, this will
    happens only one time for a file for the server's lifetime. But Im afraid
    this is not a good way to work.
    Regards
    email2us

    Hello guys
    Which is the best approach when developing
    servlet/jsp/jdbc? I will take an
    example:
    I have index-page, page2 and page 3.
    When the user writes www.mydomain.com then the page
    index.jsp checks if the
    user is coming from the servlet, like this:
    <%
    if(request.getAttribute("getPageTitle")==null){
    %>
    <jsp:forward page="/Index" />
    <%
    else{
    %>
    <%@ include file="/include/header.jsp" %>
    content for index.jsp
    <%@ include file="/include/footer.jsp" %>
    <%
    %>
    On the other hand, the Index class has this init()
    public void init(ServletConfig config) throws
    ServletException {
    super.init(config);
    con = DatabaseConf.getConnection();
    DatabaseConf is a class that handles all the
    operations related to the
    database.
    Index.class has also the doGet-method like this:
    request.setAttribute ("getPageTitle", "AnyTilte");
    getServletConfig().getServletContext().getRequestDispa
    tcher("/index.jsp").forward(request,
    response);
    Does it looks ok so long?
    Now, I have other pages, page2 and page3 (in fact I
    have mych more than just
    these, but this is only an example)
    pages.jsp works as index.jsp. It makes a check
    <%
    if(request.getAttribute("getPageTitle")==null){
    %>
    if not satisfied than it redirect to
    <jsp:forward page="/Page2" />
    My concern, however, is about databasemanagement.
    Even the Page.class has an
    init-method that looks exactly like the one in
    Index.class, e.g.
    public void init(ServletConfig config) throws
    ServletException {
    super.init(config);
    con = DatabaseConf.getConnection();
    Please use the code formatting tags when posting actual code.
    In conclusion, Im starting jdbc-connection for every
    class-file that
    initiates. Is this a good approach? You normally do not want your Servlet to initiate (which I take to mean 'startup') a database. The two can run independently. The place to initiate a database is in your operating system's startup scripts.
    What I would like
    is a solution to
    initiate the database only one time, when the server
    starts. Not everytime,
    the first time a specially class-file will be called.If you are talking about java.sql.Connection, you generally do not want to have a single connection for your entire application. Each thread should use its own connection, or transaction management/logical unit of work will be problematic, at best. You can use a connection pool to improve performance. However, from a caller's perspective, they are receiving a new connection each time.
    I know, this will
    happens only one time for a file for the server's
    lifetime. But Im afraid
    this is not a good way to work.
    Regards
    email2us- Saish

  • JDBC Helper Service

    Hello,
    The SQL Server DB Configuration in WLP Deployment Guide says JDBC Helper
    Service needs to be configured for each application deployed. Do I need to
    do this for other applications that has been installed and deployed
    out-of-box (p13nApp, p13nConsoleApp, paymentWSApp, taxWSApp, wlcsApp,
    wlpDocsApp)? I only did it for portal app so far and just got me wondered...
    Thank you,
    Makoto

    Makoto Suzuki wrote:
    Hi,
    So am I correct in thinking that the other apps are still using cloudscape
    database, although the connection pools and data sources now point to SQL
    Server after configuration is changed?I don't mean that. Those apps won't work. So, if you plan to use all the
    apps, make this change in all the apps.
    Subbu
    >
    Thank you,
    Makoto
    "Subbu Allamaraju" <subbuATBeaDOTCom> wrote in message
    news:3d08a832$[email protected]..
    Makoto,
    You need not, if you're not using those apps.
    Subbu
    Makoto Suzuki wrote:
    Hello,
    The SQL Server DB Configuration in WLP Deployment Guide says JDBC Helper
    Service needs to be configured for each application deployed. Do I need
    to
    do this for other applications that has been installed and deployed
    out-of-box (p13nApp, p13nConsoleApp, paymentWSApp, taxWSApp, wlcsApp,
    wlpDocsApp)? I only did it for portal app so far and just got mewondered...
    Thank you,
    Makoto

  • Very very urgent. Please help. JSP - JDBC connectivity.

    Hi.
    Can any one guide me the methods and steps to be followed for storing the input entered on a JSP front end into a database. Also help is needed for retrieving the data from the table and displaying on the front end. Please reply as early as possible as I am stuck in my work due to this reason. Please do reply as soon as possible,.
    Regards
    Venkat

    What part don't you understand?Here are my guesses about what the OP doesn't understand:
    >
    JSP? Yes.
    JDBC? Yes.
    Relational databases? Yes.
    Deploying Web apps? Yes.
    Your servlet/JSP container? Yes.
    What? Yes.Again, just wild guesses. :-)

  • Need serious help with JSP + JDBC/Database connection

    Hey all,
    I have to build an assignment using JSP pages. I am still pretty new and only learning through trial and error. I understand a bit now, and I have managed to get a bit done for it.
    I am having the most trouble with a Login Screen. The requirements are that the a form in a webpage has Username/Number and Password, the user clicks Login, and thats about it. The values for the username/number and password NEED to come from the database and I cannot manage to do this. The thing I have done is basically hardcode the values into the SQL statement in the .jsp file. This works, but only for that one user.
    I need it so it checks the username/number and password entered by the user, checks the database to see if they are in it, and if so, give access. I seriously am stuck and have no idea on what to do.
    I dont even know if I have made these JSP pages correct for starters, I can send them out if someone is willing to look/help.
    I have setup 3 other forms required for the assignment and they are reading data from the db and displaying within tables, I need to do this with non-hardcoded values aswell. Im pretty sure I need to use for example 'SELECT .... FROM .... WHERE username= +usrnm' (a variable instead of username="john" , this is hardcoded), I just CANNOT figure out how to go about it.
    Its hard to explain through here so I hope I gave enough info. A friend of mine gave some psuedocode i should use to make it, it seems ok to follow, its just I do not know enough to do it. He suggested:
    get the username and pass from the env vars
    open the db
    make an sql (eg SELECT user, pass FROM users WHERE user = envuser)
    index.jsp points to login.jsp
    login.jsp get the vars you put into index.jsp
    opened the db
    is the query returns nothing - then the user is wrong
    OR if the passwords dont match
    - redirect back to index.jsp
    if it does match
    - set up a session
    - redirect to mainmenu.jsp
    Anyway, thanks for any help you can give.
    -Aaron

    Hi,
    Try this... it may help you...
    mainMenu.jsp
    <html>
    <body>
    <form method="POST" action="login.jsp">
    Username: <input type="text" name="cust_no">
    <p>
    Password: <input type="password" name="password">
    <p>
    <input type="submit" value="LOGIN">
    </form>
    </body>
    </html>
    login.jsp
    <%@ page import="java.io.*, java.sql.*"%>
    <html>
    <body>
    <%
    try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection connection = DriverManager.getConnection("jdbc:odbc:rocky");
    Statement statement = connection.createStatement();
    String query = "SELECT cust_no, password FROM customers WHERE cust_no='";
    query += request.getParameter("cust_no") + "' AND password='";
    query += request.getParameter("password") + "';";
    ResultSet resSum = statement.executeQuery(query);
    if (request.getParameter("cust_no").equalsIgnoreCase(resSum.getString("cust_no") && request.getParameter("password").equalsIgnoreCase(resSum.getString("password"))
    %>
    <h2>You are logged in!</h2>
    <%
    else
    %>
    <h2>You better check your username and password!</h2>
    <%
    }catch (ClassNotFoundException cnfe){
    System.err.println(cnfe);
    }catch (SQLException ex ){
    System.err.println( ex);
    }catch (Exception er){
    er.printStackTrace();
    %>
    </body>
    </html>
    I didn't check the code that I wrote. So you may have to fix some part of it. Also this may not be the best solution, but it will help you to understand the process easily.
    The more efficient method is to check whether the result set returned from the database is null or not.... I hope you got the idea... Good luck!
    Rajesh

  • JSP + JDBC + MySql Problem (Tomcat 4.1)

    I'm completely helpless... whenever I try to retrieve stuff from the db (using a jsp page), I get errors that don't even make sense.
    out.println(stmt.executeQuery("SELECT * FROM newsTbl WHERE articleID = 1").getString("articleTitle"));if I try doing the above, I get a "ServletException : Before start of result set" error that supposedly occurred at this line of the generated servlet:
    if (pageContext != null) pageContext.handlePageException(t);---------------
    If i try this:
    ResultSet rsSec = stmt.executeQuery("SELECT * FROM newsSecTbl");
    rsSec.beforeFirst();  //<-- Even if I don't have this line the result does not change
      out.println(rsSec.next());
      while (rsSec.next()) { ... }I the while loop is never initiated, because rsSec.next() is false... kind of weird if you ask me, I even put two entries into the table to make sure the cursor wasnt at the first record and saying there was no second one (which would have been right if there were only one record).
    I would be very grateful if someone could help me out with this. I've never done any db programming with Java yet, so I dont have a clue what Im doing. By the way, I'm using MySql (indicated in the title) and the server was running and available when I ran the above code.
    Cheers,
    Tom

    You can't do this:
    out.println(stmt.executeQuery("SELECT * FROM newsTbl WHERE articleID = 1").getString("articleTitle"));The ResultSet you get back is a database cursor that doesn't point to the first row yet. The correct idiom is:
    String sql = "SELECT * FROM newsTbl WHERE articleID = 1";
    ResultSet result = stmt.executeQuery(sql);
    String articleTitle = "";
    while (result.next())
       title = result.getString("articleTitle");
    result.close();
    stmt.close();If you've never done DB programming before, I'd recommend that you click on the Tutorials link to the left and go through the JDBC tutorial carefully. You'll save yourself a lot of grief.
    Another good idea would be to separate out all your database code into at least one separate object, independent of the servlet. That way you can test and develop it off to the side until it's 100% solid. Then your servlet can simply instantiate one and use it. All your problems from that point forward will be servlet issues, because you'll know that your database code is working. - MOD
    See if that works better. - MOD

  • Newbie with JSP & JDBC questions

    Hi. I have a quick question. I have a client jsp page with a table, listing all the fields from my mySQL table called kellybclients. At the end of each row, I also have a submit button that I would like navigate the user to the campus jsp page that only shows the data associated with the client who's button they clicked on in the table. I'm trying to figure out how to pass this data from my JSP into the rowset.setCommand method in my connection/data bean. I am using a cached row set. Here's the code from my bean:
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package ETS;
    import java.sql.SQLException;
    import javax.sql.rowset.CachedRowSet;
    import java.util.ArrayList;
    import com.sun.rowset.CachedRowSetImpl;
    public class CampusDataBean {
        private CachedRowSet rowSet;
      public CampusDataBean() throws Exception
        Class.forName("com.mysql.jdbc.Driver");
        rowSet = new CachedRowSetImpl();
        rowSet.setUrl("jdbc:mysql://traderseven.nmsu.edu/is470Spring08?relaxAutoCommit=true");
        rowSet.setUsername("is470Spring08");
        rowSet.setPassword("1DoNtier");
        rowSet.setCommand("SELECT campid, clientid, campname,campcounty FROM kellybCampus WHERE clientid=?");
        CampusBean camp = new CampusBean();
        rowSet.setString(1, camp.getClientID());
        rowSet.execute();
      public ArrayList<CampusBean> getCampusList() throws SQLException
        ArrayList<CampusBean> campusList = new ArrayList<CampusBean>();
        rowSet.beforeFirst();
        while(rowSet.next())
          CampusBean campus = new CampusBean();
          campus.setCampID(rowSet.getString(1));
          campus.setClientID(rowSet.getString (2));
          campus.setCampName(rowSet.getString(3));
          campus.setCounty(rowSet.getString(4));
          campusList.add(campus);
        return campusList;
    public void addCampus(CampusBean campus) throws SQLException
        rowSet.moveToInsertRow();
        rowSet.updateString(1,campus.getCampID());
        rowSet.updateString(2,campus.getClientID());
        rowSet.updateString(3,campus.getCampName());
        rowSet.updateString(4,campus.getCounty());
        rowSet.insertRow();
        rowSet.moveToCurrentRow();
        rowSet.acceptChanges();
    }I'm sorry if this is too vague. I'd appreciate any help, fixes, or pointers on where to learn how to do this. Thank you again.
    KellyJo

    So the button should be a Submit button for a form. There are a couple of different methods for doing this:
    1) Each row on the table can be a different form, each form uses the same action (servlet) target and has a hidden input with a unique identifier for each of the clients:
    <table>
      <tr><form action="selectClient" method="post"><td> etc </td><td><input type="hidden" name="id" value="1"/><input type="submit"/></td></form></tr>
      <tr><form action="selectClient" method="post"><td> etc </td><td><input type="hidden" name="id" value="2"/><input type="submit"/></td></form></tr>2) Use a single form with a button type=submit for each row with different values (Note: This is broken in IE7 so you probably shouldn't use it)
    <table><form action="selectClient" method="post">
      <tr><td> etc </td><td><button type="submit" name="id" value="1">Submit</button></td></tr>
      <tr><td> etc </td><td><button type="submit" name="id" value="2">Submit</button></td></tr>3) Use a single form, have a hidden value with a blank value. Each row has a submit button with a javascript onclick method that sets the form's hidden value to one appropriate to the row, then submits the form. I won't show you this code but there are examples on the web.
    4) Use a single form with an input="submit" element on each row. Each button would have a different name with the ID info encoded in it, then you would have server-side code that takes parameters, finds the right one and parses out the proper row to edit:
    <table><form action="selectClient" method="post">
      <tr><td> etc </td><td><input type="submit" name="submit__id_1"/></td></tr>
      <tr><td> etc </td><td><input type="submit" name="submit__id_2"/></td></tr>I think most people end up doing some variant of 3, which I don't like because I hate to rely on JavaScript to make my web apps work properly. I would prefer 4, which takes more work on the server side (which I like better) but 1 works just as well with a lot more typing and uglier HTML code. Actually, I would like 2 the best because that is pretty much what the <button> element was designed for, but Microsoft screwed that up.

  • Jsp errot help!

    i have 4 error after compling this files, cannot 1 help pls!
    <%@ page import="java.io.*"%>
    <%@ page import="java.util.zip.*"%>
    <%@ page import="java.lang.Thread"%>
    <%@ page import="java.net.URL"%>
    <%@ page import="java.net.URLConnection"%>
    <%@ page import="java.sql.*"%>
    <%@ page import="java.util.*"%>
    <%@ page import="java.util.StringTokenizer.*"%>
    <%
    class ThreadBase implements Runnable
    int counter = 0;
    public void run()
         try
              Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
         catch(ClassNotFoundException e)
              System.out.println(e);
         Connection c = DriverManager.getConnection("jdbc:odbc:MHuman");
         Statement s = c.createStatement();
              int x = 1;
              String x_str = "";
              do{
                        x_str = Integer.toString(x);
                        if (x==23) x_str = "X";
                        else if (x==24) x_str="Y";
                   try
                        String sqlstr = "CREATE TABLE Chromosome"+x_str+" " +
                        "(ID number, HChr varchar (20), Hstart number, Hend number, MChr varchar (20), Mstart number, Mend number)";
                        System.out.println(sqlstr);
                        try { s.execute("Drop table Chromosome"+x_str+"");
                   catch (Exception e) { };
                   s.execute(sqlstr);
    catch(SQLException e)
    e.printStackTrace();
    // Create BufferedReader object.
    BufferedReader br = null;
    try
              br = new BufferedReader(
              new FileReader("C:\\downloadChr\\mhuman\\chr"+x_str+".txt"));
    catch(IOException e)
         System.out.println(e);
    String line, ID, HChr, Hstart, Hend, MChr, Mstart, Mend, sql;
    StringTokenizer st;
    try
         cs();
         while ((line = br.readLine()) != null)
                   st = new StringTokenizer(line, " ");
                   ID = st.nextToken();
                   HChr = st.nextToken();
                   Hstart = st.nextToken();
                   Hend = st.nextToken();
                   MChr = st.nextToken();
                   Mstart = st.nextToken();
                   Mend = st.nextToken();
                   if (!MChr.startsWith("chrNA"))
                        if (!MChr.startsWith("chrM"))
                             if (!MChr.startsWith("chrUn"))
                                  if (!MChr.startsWith("chrFinished"))
                        sql = "INSERT INTO Chromosome"+x_str+" " +
                        "VALUES (" + ID + ", '" + HChr + "', " + Hstart + ", " + Hend + ", '" + MChr + "', " + Mstart + ", " + Mend + ")";
                        //System.out.println(sql);
                        s.executeUpdate(sql);
    catch(IOException e)
    System.out.println(e);
    }while (x++ < 12);
         c.close();
         private void cs()
              int a = counter;
              a++;
              counter = a;
              System.out.println("Thread is running with Chr " + counter);
    C:\Program Files\Tomcat 4.1\work\Standalone\localhost\examples\jsp\HMC\HTML\testDL3_jsp.java:74: unreported exception java.sql.SQLException; must be caught or declared to be thrown
    An error occurred at line: 9 in the jsp file: /jsp/HMC/HTML/testDL3.jsp
    Generated servlet error:
         Connection c = DriverManager.getConnection("jdbc:odbc:MHuman");
    ^
    An error occurred at line: 9 in the jsp file: /jsp/HMC/HTML/testDL3.jsp
    Generated servlet error:
    C:\Program Files\Tomcat 4.1\work\Standalone\localhost\examples\jsp\HMC\HTML\testDL3_jsp.java:76: unreported exception java.sql.SQLException; must be caught or declared to be thrown
         Statement s = c.createStatement(); ^
    An error occurred at line: 9 in the jsp file: /jsp/HMC/HTML/testDL3.jsp
    Generated servlet error:
    C:\Program Files\Tomcat 4.1\work\Standalone\localhost\examples\jsp\HMC\HTML\testDL3_jsp.java:139: unreported exception java.sql.SQLException; must be caught or declared to be thrown
                        s.executeUpdate(sql);
    ^
    An error occurred at line: 9 in the jsp file: /jsp/HMC/HTML/testDL3.jsp
    Generated servlet error:
    C:\Program Files\Tomcat 4.1\work\Standalone\localhost\examples\jsp\HMC\HTML\testDL3_jsp.java:153: unreported exception java.sql.SQLException; must be caught or declared to be thrown
         c.close();
    ^
    4 errors

    Your Connection object and Statement object is written outside try{}.
    Put all your code inside try{}.
    Hope this will solve your problem.

  • Formatting data in table - jsp & jdbc

    Hey there friends!
    I was having a little problem formatting data and I was looking for help!
    I want to format the data from jdbc as follows on a jsp page
    THIS IS REPORT TO GENERATE
    Name | Worked | Refused | Training | CarryOver
    Jim | 10 | 5 | 2 | 5
    Bob | 20 | 5 | 10 |
    The resultset that I retrieve from my database is like this
    RESULTSET
    ID | Name | Type | Hours | CarryOver
    1 | Jim | Worked | 10 | 5
    1 | Jim | Refused | 5 | 5
    1 | Jim | Training | 10 | 5
    2 | Bob | Worked | 20 | 10
    2 | Bob | Training | 5 | 10
    Can anyone suggest what can be a done here?

    As you have learnt something it is only fair for me for reciprocate.
    The code example I gave you was psuedocode - not real java. You need to add in a couple more things to make it work correctly.
    First we want to create an entry in the hash, iff there is no record already there, otherwise, we want to get the value and add our new value to it (let's say the map is called map):
    String key = record.name + "/" + record.type;  // Using combination string as the key - simplest solution
    Long hours = map.get(key);
    if (hours == null) {
       hours = new Long(record.hours);
    } else {
       hours = new Long(hours.getValue() + record.hours);
    map.put(key, hours);It would be better to use your own class to hold the long value - as this would save all the construction calls.

  • Paging in JSP(Scriptlets) help-me! help-me! help-me!

    Somebody can order an example of paging in JSP. does not obtain to make the paging.... Please, somebody can help.....� an urgency case me! In case that somebody has some example please, [email protected] orders pro email If possivel in Scriptlets
    Very Obliged!

    <%@ page import="java.sql.*" %>
    <%@ page errorPage="err.jsp" %>
    <%
    By VendeW and Shibayama
    %>
    <html>
    <body>
    <center>
    <h2>Pagina��o usando JSP e MySQL</h2>
    <table border="2">
    <tr bgcolor="tan">
    <th>id</th><th>Titulo</th><th>Image</th><th>Descri��o</th></tr>
    <%
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
    Connection conexao = DriverManager.getConnection("jdbc:odbc:book");
    Statement declaracao = conexao.createStatement();
    Statement declaracao2 = conexao.createStatement();
    int limitePorPagina = 5;
    ResultSet resultado = declaracao.executeQuery("Select * from tbl_livro limit " + request.getParameter("pr") + "," + String.valueOf(limitePorPagina));
    ResultSet rs2 = declaracao2.executeQuery("Select count(*) as c from tbl_livro");
    rs2.next();
    int totalregs = Integer.parseInt(rs2.getString("c"));
    %>
    <b>Total de Registros: </b><%=totalregs%>
    <%
    int totalpgs = Math.round(totalregs / limitePorPagina);
    out.write("<b>P�ginas:</b> " + totalpgs);
    if ((totalregs % limitePorPagina) > 0) totalpgs++;
    int pr = Integer.parseInt(request.getParameter("pr"));
    try {
    while (resultado.next()) {
    String id = resultado.getString("id_livro");
    String nm = resultado.getString("nm_livro");
    String img = resultado.getString("image");
    String desc = resultado.getString("desc_livro");
    %>
    <tr>
    <td><%=id%> </td>
    <td><%=nm%> </td>
    <td><%=img%> </td>
    <td><%=desc%> </td>
    </tr>
    <%
    }//while (resultado.next())
    %>
    </table>
    <%
    }//try
    catch (SQLException e) { out.println("SQL Error" + e); }
    if (pr > 0) {
    %>
    [Primeira P�gina] 
    <a href="?pr=<%=pr-limitePorPagina%>">[Anteriores]</a> 
    <%
    }//if (pr > 0)
    if (pr < (totalpgs * limitePorPagina) - limitePorPagina) {
    %>
    <a href="?pr=<%=pr+limitePorPagina%>">[Pr�ximos]</a> 
    <a href="?pr=<%=(totalpgs * limitePorPagina) - limitePorPagina%>">[Ultima P�gina]</a> 
    <%
    }//if (cont < totalpgs)
    %>
    </center>
    </body>
    </html>

  • Language problem in JSP please help

    Hi all java guru;
    Altough I tried all different way I can not solve the my problem.
    My problem is Turkish language problem in JSP.
    If my jsp page use database applications such as push or pull data to my SQL 2000 database or call some datas from database, some data which contains turkish caracter are seen wrong. suc as ����� is to ??????
    what is the problem?
    But important point is that; this is only Database data which come from sql database. But I can see JSP data or HTML data truly.
    I try different method to solve in JSP page;
    1-request.setEncoding("iso-8859-9");
    or
    request.setCharacterEncoding( "windows-1250" );
    2-
    @contentType="text/html; charset=iso-8859-9"
    @page pageEncoding="iso-8859-9"
    3-
    <meta http-equiv="Content-Language" content="tr">
    <META http-equiv="Content-Style-Type" content="text/css">
    4-
    ISO-8859-9 is turkish charecter spefications
    String TR_tlp = new String(NEW_TALEP.getBytes(),"ISO-8859-9"); // this parm is inserting database but problem is go on.
    5-
    for the database...
    Properties props = new Properties();
    props.put("user","login");
    props.put("password","password");
    props.put("charSet","UNICODE");
    6-
    url= "jdbc:microsoft:sqlserver://IP_NO:1433;databasename=database;TRUSTED_CONNECTION = true;CHARSET="+sun.io.ByteToCharConverter.getDefault().getCharacterEncoding();
    or
    url= "jdbc:microsoft:sqlserver://IP_NO:1433;databasename=database;TRUSTED_CONNECTION = true;CHARSET=ISO-8859-9"
    con= DriverManager.getConnection(url, kulad, sifre);
    I am using tomcat 5.0.19,
    is there any way to solve this problem... Please help......

    Were you ever able to solve your problem?
    I have a similar problem.
    My database is storing the characters correctly and they can be viewed in Java, but when I try to convert them to unicode using:
    String inputUtf8 = new String(input.getBytes(),charset);
    it works for almost all characters, but some come through as noncharacter "boxes."
    The characters that come through as boxes in iso8859-1 are the ones that are in the "supplementary" character range of that set, such as:
    - curved left and right quotes
    - "TM" symbol
    - bullets
    - m dash and n dash
    (see this table: http://www.csgnetwork.com/htmlchrset.html for a more complete list of the supplementary characters )
    Any idea what I need to do to have these characters show up properly?

  • JSP & JDBC

    Hi. I have researched JSP, but would like to learn how to use JDBC. I am currently trying to create a forum, but need a basic tutorial of how to connect the two together. A simple, very basic website will do, and it would be great if I could see primitive sample codes of using JSP to access and manipulate a database.
    Best regards,
    Ben.

    Hello
    I would suguest you not connect to database from JSP but instead use Bean for this job. It's more right thing to do , and leave JSP as less code as posible.
    Here is exemple code that i made for myself (connecting to MySql)
    *  Class for SqlBase query to get the menu from Mysql database
    *      EXEMPLE OF CONNECTING TO MYSQL WITH JDBC BY QUERY
    *            Connection conn = null;
    *            Class.forName("com.mysql.jdbc.Driver").newInstance();
    *            conn = DriverManager.getConnection(connStr);
    *            Statement s = conn.createStatement();
    *            String query = "Select menu_id, menu_name, menu_link from blog_menu";
    *            ResultSet resultset = s.executeQuery(query);
    *      EXEMPLE OF CONNECTING TO MYSQL WITH JDBC BY USING STORED PROCEDURES
    *           Connection conn = null;
    *           Class.forName("com.mysql.jdbc.Driver").newInstance();
    *           conn = DriverManager.getConnection(connStr);
    *           CallableStatement cStmt = conn.prepareCall("{call sp_BlogMenu()}");
    *           cStmt.execute();
    *           ResultSet resultset = cStmt.getResultSet(); 
    *                      OR INSTEAD OF TWO LAST LINES IT'S CAN BE DONE
    *          ResultSet resultset =  cStmt.executeQuery();
    *      CLOSING CONNECTION
    *          if( conn != null )
    *               conn.close();
    *               s.close();
    *               cStmt.close();
    *               resultset.close();
    */Hope it helps.

Maybe you are looking for