JSP with MYSQL.

Dear Friends
I have a unique problem in java, when i try to connect to mysql db.
It shows an error message:
Unable to load driver. Getting Connection ... SQLException: No suitable driverI am using mysql MySQL 4.1.9 and tomcat 5.5 version.
though i have loaded the driver in lib directory, it still displays the same error
messgae. Here is the jsp file which i use to connect to my database.
http://localhost:8080/mysqljdbc.jsp
<%@ page import="java.net.*" %>
<%@ page import="java.util.*" %>
<%@ page import="java.io.*" %>
<%@ page import="java.sql.*" %>
<%
     try{
     Class.forName("com.mysql.jdbc.Driver").newInstance();
     catch (Exception E) {
     out.println("Unable to load driver.");
     E.printStackTrace();
     try{
          out.println("Getting Connection ...");
          Connection C = DriverManager.getConnection("jdbc:mysql://localhost:3306/vinoth");
          out.println("<br>Connected:  " + !C.isClosed() + "<br>\n");
          out.println("Catalog:  " + C.getCatalog() + "<br>\n");
               Statement S = C.createStatement();
               ResultSet rs = S.executeQuery("SELECT * FROM foo");
               ResultSetMetaData rsStruc = rs.getMetaData();
               out.println("Table:  " + rsStruc.getTableName(1) + "<br>");
               out.println("<table bgcolor=c8c8c8 cellpadding=5 cellspacing=1>");
               out.println("<tr bgcolor=000000>");
               int colCount = rsStruc.getColumnCount();
               String colName = "";
               for(int i=1;i <= colCount; i++){
               colName = rsStruc.getColumnName(i) ;
               out.println("<td><B><font color=white>" + colName + "</font></b></td>\n");
               out.println("</tr>");
               while (rs.next()) {
               out.println("<tr bgcolor=ffffff>");
               for(int i=1;i <= colCount; i++){
               colName = rsStruc.getColumnName(i) ;
               String fld = rs.getString(colName);
                    out.println("<td>" + fld + "</td>");
               out.println("</tr>");
               out.println("</table>");
               rs.close();
               C.close();
     catch (Exception E) {
      out.println("SQLException: " + E.getMessage());
%>Now is there anything i have to configure apart from this.
Thanx in advance.

First things first...i definitely recommend you take out the db stuff out of the jsp page. Place the logic in a DAO and if you have to reference the dao in the jsp. Although in a practice you should have a service layer which does the db stuff. Use a servlet to call the service layer and pass the results of the service layer to the jsp.
Writing java code like that in the jsp is just bad programming. There are loads of web frameworks that enable you to develop scalable web applications.
I realise that this does not help you but it is a good idea to get the design correct before embarking on the development.

Similar Messages

  • JSP with MYSQL 4.0

    May i know is JSP works well with MYSQL 4.0 database?

    Yaah..it works perfectly OK....just download the required driver my mysql site only & ur ready to develop applications is JSP using mysql.

  • Dependant lovs in jsp with mysql data

    hi to all.
    here is my doubt
    How to create dependant dynamic list of values in jsp where the data comes from mysql tables.(I mean i am storing all the details in mysql tables using foreign keys etc..).
    Ex.:country--->state--->district--->city--->
    we will be having this in most of the sites in general.
    Hope u got what i am looking for
    Expecting a very quick and excellent answer.
    thank you

    Within jsp pages it is not possible to have the comboboxes dynamically updated without intervention to either refresh the page with the new data or use java script.
    I had a similar problem which i resolved with java script :
    Interactive combo boxes on jsp
    Have a look at this thread for more info.

  • JSP with MySQL connection in Tomcat6.0.20

    Hi i'm using MySQL5.1, Tomcat6.0.20 in my project, There i'm not able to connect to the database. it's giving the error.
    My program is :
    <%@ page language="java" import="java.sql.*" %>
    <%
         String driver = "org.gjt.mm.mysql.Driver";
         Class.forName(driver).newInstance();
         try{
              String url="jdbc:mysql://localhost/books?user=root@localhost&password=india123";
              Connection con=DriverManager.getConnection(url);
              Statement stmt=con.createStatement();
         catch(Exception e){
              System.out.println(e.getMessage());
         if(request.getParameter("action") != null){
              String bookname=request.getParameter("book_name");
              String author=request.getParameter("author");
              stmt.executeUpdate("insert into books_lib(book_name,author) values('"+bookname+"','"+author+"')");
              ResultSet rst=stmt.executeQuery("select * from books_lib");
              %>
              <html>
              <body>
              <center>
                   <h2>Books List</h2>
                   <table border="1" cellspacing="0" cellpadding="0">
                   <tr>
                        <td><b>S.No</b></td>
                        <td><b>Book Name</b></td>
                        <td><b>Author</.b></td>
                   </tr>
                        <%
                        int no=1;
                        while(rst.next()){
                        %>
                        <tr>
                        <td><%=no%></td>
                        <td><%=rst.getString("book_name")%></td>
                        <td> <%=rst.getString("author")%> </td>
                        </tr>
                        <%
                        no++;
         rst.close();
         stmt.close();
         con.close();
    %>
                   </table>
                   </center>
              </body>
         </html>
    <%}else{%>
         <html>
         <head>
              <title>Book Entry FormDocument</title>
              <script language="javascript">
              function validate(objForm){
                   if(objForm.bookname.value.length==0){
                   alert("Please enter Book Name!");
                   objForm.bookname.focus();
                   return false;
                   if(objForm.author.value.length==0){
                   alert("Please enter Author name!");
                   objForm.author.focus();
                   return false;
                   return true;
                   </script>
              </head>
              <body>
                   <center>
    <form action="BookEntryForm.jsp" method="post" name="entry" onSubmit="return validate(this)">
         <input type="hidden" value="list" name="action">
         <table border="1" cellpadding="0" cellspacing="0">
         <tr>
              <td>
                   <table>
                        <tr>
                        <td colspan="2" align="center">
    <h2>Book Entry Form</h2></td>
                        </tr>
                        <tr>
                        <td colspan="2"> </td>
                        </tr>
                        <tr>
                        <td>Book Name:</td>
                        <td><input name="bookname" type="text" size="50"></td>
                        </tr>
                        <tr>
                        <td>Author:</td><td><input name="author" type="text" size="50"></td>
                        </tr>
                        <tr>
                             <td colspan="2" align="center">
    <input type="submit" value="Submit"></td>
                             </tr>
                        </table>
                   </td>
              </tr>
         </table>     
    </form>
                   </center>
              </body>
         </html>
    <%}%>
    The error page is:
    HTTP Status 500
    org.apache.jasper.JasperException: Unable to compile class for JSP:
    An error occurred at line: 19 in the jsp file: /singleupload/BookEntryForm.jsp
    stmt cannot be resolved
    16:      if(request.getParameter("action") != null){
    17:           String bookname=request.getParameter("book_name");
    18:           String author=request.getParameter("author");
    19:           stmt.executeUpdate("insert into books_lib(book_name,author) values('"+bookname+"','"+author+"')");
    20:           ResultSet rst=stmt.executeQuery("select * from books_lib");
    21:           %>
    22:           <html>
    An error occurred at line: 20 in the jsp file: /singleupload/BookEntryForm.jsp
    stmt cannot be resolved
    17:           String bookname=request.getParameter("book_name");
    18:           String author=request.getParameter("author");
    19:           stmt.executeUpdate("insert into books_lib(book_name,author) values('"+bookname+"','"+author+"')");
    20:           ResultSet rst=stmt.executeQuery("select * from books_lib");
    21:           %>
    22:           <html>
    23:           <body>
    An error occurred at line: 45 in the jsp file: /singleupload/BookEntryForm.jsp
    stmt cannot be resolved
    42:                     no++;
    43:      }
    44:      rst.close();
    45:      stmt.close();
    46:      con.close();
    47: %>
    48:                </table>
    An error occurred at line: 46 in the jsp file: /singleupload/BookEntryForm.jsp
    con cannot be resolved
    43:      }
    44:      rst.close();
    45:      stmt.close();
    46:      con.close();
    47: %>
    48:                </table>
    49:                </center>
    Stacktrace:
         org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:92)
         org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:330)
         org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:439)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:334)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:312)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:299)
         org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:586)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:317)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    Please help me

    ?An error occurred at line: 20 in the jsp file: /singleupload/BookEntryForm.jsp stmt cannot be resolved
    That means it can't see any variable declared called "stmt"
    There isn't one at this point.
    The stmt variable you have declared up above, is nested in curly braces - within your try/catch statement. As such it only has scope within those curly braces. If you want to use stmt outside of the try block, you need to declare stmt outside of it.
    And yes, I echo Balusc's comments about scriptlet code in a jsp page.
    A better solution would be to write a java class with a method that does the database query, and returns a List of objects.
    Your JSP can then take that list of objects and display them on the page.
    Its a bit more work, but makes the code much easier to write/maintain/test because you separate out the "data" and "view" layers.

  • How to connect JSP with MySql Database?

    HI All...
    I want to know or How to connect Mysql with JSP or JSF any other software is available? please help me.....

    I want to know or How to connect Mysql
    with JSP or JSF any other software isavailable?
    please help me.....First you need to find 25 m of a CatV cable and...The DB files need to be located on the ninth device of a SCSI Daisy Chain with the total SCSI cable length being over 150 m (and the devices (and cables) need to be mix of Differential and Non-Differential).
    Edit: And forget the terminator, who needs it?

  • JSP with mysql database

    *********************This is my HTML form for Media search*****************
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN">
    <html>
    <head>
    <meta content="text/html; charset=ISO-8859-1"
    http-equiv="content-type">
    <title>search media form</title>
    </head>
    <body>
    <form name="search" action="med_search.jsp"> <big
    style="font-weight: bold; color: rgb(0, 102, 0);">Media
    : Search<br>
    </big>
    <hr
    style="height: 1px; width: 50%; margin-left: 0px; margin-right: auto;"><label>Media
    :   equals :</label><big
    style="font-weight: bold; color: rgb(0, 102, 0);">  
    <select size="1" name="msearch_name">
    <option>-All-</option>
    <option>100% Home Girls</option>
    <option>1800mumanddad</option>
    <option>2D Max</option>
    <option>Access all areas</option>
    <option>Adelaide Advertiser</option>
    <option>Adelaide Messenger</option>
    <option>Adelaide Sunday Mail TV guide</option>
    <option>All Media</option>
    <option>Ari Reserved</option>
    <option>Austar</option>
    <option>Blockbuster</option>
    <option>Brisbane Courier Mail</option>
    <option>Brisbane Quest</option>
    <option>Brisbane Sunday Mail- TV guide</option>
    <option>Cleo</option>
    <option>Community</option>
    <option>Cosmo</option>
    <option>Day Time TV</option>
    <option>Dolly</option>
    <option>Edge</option>
    <option>Empire</option>
    <option>EMS</option>
    <option>Explode</option>
    <option>Facing Sanity</option>
    <option>Fairfax</option>
    <option>FHM</option>
    <option>Foxtel</option>
    <option>Funkysexycool</option>
    <option>Gametel newsletter</option>
    <option>Gametel Sim Pack</option>
    <option>Gametel UI 1st Version</option>
    <option>Gametel UI 2nd Version</option>
    <option>Gametel Website</option>
    <option>Geelong Advertiser-TV guide</option>
    <option>Girlfriend</option>
    <option>Good Medicine</option>
    <option>Herald Sun</option>
    <option>Home Girls</option>
    <option>Insight</option>
    <option>MailBlast</option>
    <option>Maximum Performance</option>
    <option>Melboume Leader</option>
    <option>Mobile</option>
    <option>Mobile Pet-Ari</option>
    <option>Money Saver</option>
    <option>Motor Show Mag</option>
    <option>Mr.Wisdoms Whopper</option>
    <option>MTV</option>
    <option>Music Australia</option>
    <option>New Chat</option>
    <option>New Idea</option>
    <option>NW Magazine</option>
    <option>One Love</option>
    <option>Optus</option>
    <option>Penthouse</option>
    <option>People</option>
    <option>Picture</option>
    <option>Picture Premium Edition</option>
    <option>Picture Premium Special</option>
    <option>Platinum Girls</option>
    <option>Phychic Business Cards</option>
    <option>Phychic Calender</option>
    <option>Phychic CD Cover</option>
    <option>Ralph</option>
    <option>Sain Magazine</option>
    <option>Sanity Chart</option>
    <option>Series 40 gametel subscriber</option>
    <option>Series 60 gametel community</option>
    <option>Series 60 gametel non-subscriber</option>
    <option>Series40 non-subscriber</option>
    <option>Smash Hits</option>
    <option>SMS Chat</option>
    <option>Soap World</option>
    <option>SPAM</option>
    <option>STM-WA</option>
    <option>Stupid People Line</option>
    <option>Sunday Herald Sun TV guide</option>
    <option>Sunday Telegraph TV guide</option>
    <option>Sunday Times TV guide</option>
    <option>Sydney Cumberland</option>
    <option>Sydney Daily telegraph</option>
    <option>Take 5</option>
    <option>Tasmania TV guide</option>
    <option>That's Life</option>
    <option>Total Gamer</option>
    <option>TV 10</option>
    <option>TV 7</option>
    <option>TV 9</option>
    <option>TV Hits</option>
    <option>TV Soap</option>
    <option>TV Week</option>
    <option>UNASSIGNED</option>
    <option>Urban Hits</option>
    <option>VH1</option>
    <option>Video Ezy</option>
    <option>Vogue Girl</option>
    <option>WAP</option>
    <option>Web Competitions</option>
    <option>Website</option>
    <option>West Magazine</option>
    <option>Western Australian</option>
    <option>What DVD</option>
    <option>What's Hot on Video</option>
    <option>Witchcraft</option>
    <option>Women's Day</option>
    <option>xxx</option>
    </select>
    <br>
    <span style="font-weight: bold;"><span
    style="color: rgb(0, 102, 0);"><span
    style="font-weight: bold;"><span
    style="font-weight: bold;"></span></span></span></span></big><big
    style="font-weight: bold; color: rgb(0, 102, 0);">  
          </big><big
    style="color: rgb(0, 102, 0);"><small><label
    style="color: rgb(0, 0, 0);">or
    is like :</label></small></big><big
    style="font-weight: bold; color: rgb(0, 102, 0);">  
    <textarea cols="20" rows="1" name="msearch_like"></textarea><br>
         </big><label
    style="color: rgb(0, 0, 0);">Media Type
    :</label><big style="font-weight: bold; color: rgb(0, 102, 0);">
    <select size="1" name="msearch_type">
    <option>-All-</option>
    <option>magazine</option>
    <option>newspaper</option>
    <option>other</option>
    <option>tv</option>
    <option>tv guide</option>
    </select>
    <br>
    <br>
    </big> <input name="med_search" value="Search"
    type="submit">  <input name="med_reset"
    value="Reset" type="reset"></form>
    <br>
    <br>
    </body>
    </html>
    //After clicking search button it will go to this jsp and gets the searched records.
    ***********************************med_search.jsp***********************
    <html>
    <body>
    <h1>Search Media</h1>
    <%@page contentType="text/html"%>
    <%@page pageEncoding="UTF-8"%>
    <%--
    The taglib directive below imports the JSTL library. If you uncomment it,
    you must also add the JSTL library to the project. The Add Library... action
    on Libraries node in Projects view can be used to add the JSTL 1.1 library.
    --%>
    <%--
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    --%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
    <%@ page import="java.sql.*" %>
    <% Connection con=null;%>
    <% PreparedStatement pstmt=null;%>
    <%
    try
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    con = DriverManager.getConnection("jdbc:mysql://silverbullet:3306/elmophish", "sirisha", "gametel123");
    out.println("<table border=0>");
    if(request.getParameter("msearch_name").equals("-All-")&request.getParameter("msearch_type").equals("-All-"))
    %>
    <jsp:forward page="med_search.html"/>
    <%
    else if(!(request.getParameter("msearch_name").equals("-All-"))&!(request.getParameter("msearch_type").equals("-All-")))
    pstmt=con.prepareStatement("select media.media_name,media.media_code,media_types.media_type,media_genders.media_gender,media.target_age,publishers.publisher,media.is_bookable,media_id from media,media_types,media_genders,publishers where media_name in (select media_name from media where media_type_id in (select media_type_id from media_types where media_type=" + "'" + request.getParameter("msearch_type") + "'" +") and media.media_name =" + "'" + request.getParameter("msearch_name") +"'" + ")and media.media_type_id=media_types.media_type_id and media.target_gender_id=media_genders.media_gender_id and media.publisher_id=publishers.publisher_id");
    out.println("<th></th><th><b>Name</b>&nbsp</th><th><b>Code</b>&nbsp</th><th><b>Type</b>&nbsp</th><th><b>Gender</b>&nbsp</th><th><b>Age</b>&nbsp</th><th><b>Publisher</b>&nbsp</th><th><b>Active</b>&nbsp</th>");
    else if(!(request.getParameter("msearch_name").equals("-All-"))&&(request.getParameter("msearch_type").equals("-All-")))
    pstmt=con.prepareStatement("select media_name,media_code,media_type,media_gender,target_age,publisher,is_bookable,media_id from media me inner join media_types mt on me.media_type_id = mt.media_type_id inner join media_genders mg on mg.media_gender_id = me.target_gender_id inner join publishers pub on pub.publisher_id = me.publisher_id where media_name="+"'"+request.getParameter("msearch_name")+"'"+"") ;
    out.println("<th></th><th><b>Name</b>&nbsp</th><th><b>Code</b>&nbsp</th><th><b>Type</b>&nbsp</th><th><b>Gender</b>&nbsp</th><th><b>Age</b>&nbsp</th><th><b>Publisher</b>&nbsp</th><th><b>Active</b>&nbsp</th>");
    else if(request.getParameter("msearch_name").equals("-All-")&!(request.getParameter("msearch_type").equals("-All-")))
    pstmt=con.prepareStatement("select media_name,media_code,media_type,media_gender,target_age,publisher,is_bookable,media_id from media me inner join media_types mt on me.media_type_id = mt.media_type_id inner join media_genders mg on mg.media_gender_id = me.target_gender_id left join publishers pub on pub.publisher_id = me.publisher_id where media_type=" + "'"+request.getParameter("msearch_type")+"'"+"");
    out.println("<th></th><th><b>Name</b>&nbsp</th><th><b>Code</b>&nbsp</th><th><b>Type</b>&nbsp</th><th><b>Gender</b>&nbsp</th><th><b>Age</b>&nbsp</th><th><b>Publisher</b>&nbsp</th><th><b>Active</b>&nbsp</th>");
    ResultSet rst=pstmt.executeQuery();
    ResultSetMetaData rsmd=rst.getMetaData();
    int n=rsmd.getColumnCount();
    while(rst.next())
    out.println("<tr>");
    %>
    <td><form action="test.jsp" method="post"> <a href="t.jsp?media_id=<% out.print(rst.getString(8)); %>">Edit</a></form></td>
    <%
    out.print("<td>"+rst.getString(1)+"</td>");
    out.print("<td>"+rst.getString(2)+"</td>");
    out.print("<td>"+rst.getString(3)+"</td>");
    out.print("<td>"+rst.getString(4)+"</td>");
    out.print("<td>"+rst.getString(5)+"</td>");
    out.print("<td>"+rst.getString(6)+"</td>");
    out.print("<td>"+rst.getString(7)+"</td>");
    out.print("</tr>");
    }catch(Exception e)
    out.println(e);
    finally
    con.close();
    %>
    <%--
    This example uses JSTL, uncomment the taglib directive above.
    To test, display the page like this: index.jsp?sayHello=true&name=Murphy
    --%>
    <%--
    <c:if test="${param.sayHello}">
    <!-- Let's welcome the user ${param.name} -->
    Hello ${param.name}!
    </c:if>
    --%>
    </body>
    </html>
    //In this search output we have edit button for each row.After we click search it will enter into another form where we can edit the record.
    //In this jsp,i have designed the form for editing and displayed the current record values as initial values and after edit it must save and update the DB.But before I click save changes,its updating the DB with all zeros.
    ******************edit_search.jsp**************************************
    <%@page contentType="text/html"%>
    <%@page pageEncoding="UTF-8"%>
    <%--
    The taglib directive below imports the JSTL library. If you uncomment it,
    you must also add the JSTL library to the project. The Add Library... action
    on Libraries node in Projects view can be used to add the JSTL 1.1 library.
    --%>
    <%--
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    --%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <h1>Edit Search</h1>
    </head>
    <body>
    <%@ page import="java.sql.*" %>
    <% Connection con=null;%>
    <% String str1,str2,str3,str4,str5,str6;%>
    <%
    try
    int mgid=0;
    int tage=0;
    int pid=0;
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    con = DriverManager.getConnection("jdbc:mysql://silverbullet:3306/elmophish", "sirisha", "gametel123");
    PreparedStatement pstmt=con.prepareStatement("SELECT media_name,media_code,media_type,media_gender,target_age,publisher,is_bookable FROM media m INNER JOIN media_types met ON m.media_type_id = met.media_type_id INNER JOIN media_genders meg ON m.target_gender_id = meg.media_gender_id LEFT JOIN publishers pubs ON m.publisher_id = pubs.publisher_id where media_id=" + "'"+request.getParameter("media_id")+"'");
    ResultSet rs=pstmt.executeQuery();
    ResultSetMetaData rsmd=rs.getMetaData();
    int n=rsmd.getColumnCount();
    while(rs.next())
    %>
    <form method="post" action="">
    <label>Name</label> <%=rs.getString("media_name")%><br>
    <label>Code</label> <textarea cols="20" rows="1"name="med_code"><%=rs.getString("media_code")%></textarea><br>
    <label>Type</label> <%=rs.getString("media_type")%><br>
    <label>Target Gender</label>&nbsp
    <% PreparedStatement pstmt2=con.prepareStatement("SELECT media_gender FROM media_genders");
    ResultSet rst1=pstmt2.executeQuery();
    ResultSetMetaData rstmd2=rst1.getMetaData();
    int cnt1=rstmd2.getColumnCount();
    %>
    <select name="tar_gen">
    <%
    while(rst1.next())
    %>
    <option><%=rst1.getString("media_gender")+"<br>"%></option>
    <%
    %>
    </select><br>
    <label>Target Age</label> <textarea cols="20" rows="1" name="med_age"><%=rs.getString("target_age")%></textarea><br>
    <label>Publisher</label> 
    <%
    PreparedStatement pstmt1=con.prepareStatement("SELECT publisher FROM publishers");
    rst1=pstmt1.executeQuery();
    ResultSetMetaData rstmd1=rst1.getMetaData();
    int cnt2=rstmd1.getColumnCount();
    %>
    <select name="pub">
    <%
    while(rst1.next())
    %>
    <option><%=rst1.getString("publisher")+"<br>"%></option>
    <%
    %>
    </select><br>
    <label>Bookable</label> 
    <input type="checkbox">
    <%
    if (rs.getString("is_bookable").equals("1"))
    %>
    <checkbox maxlength="20" <checked></checkbox>
    <%
    else
    %>
    <checkbox maxlength="20" <unchecked></checkbox>
    <%
    %>
    <%
    str1=request.getParameter("med_code");
    PreparedStatement pst2=con.prepareStatement("select media_gender_id from media_genders where media_gender = "+ "'" + request.getParameter("med_gen") +"'");
    ResultSet rst2=pst2.executeQuery();
    while(rst2.next())
    mgid=rst2.getInt(1);
    rst2.close();
    str2=request.getParameter("med_gen");
    try
    tage=Integer.parseInt("'"+request.getParameter("med_age")+"'");
    catch(NumberFormatException e){}
    PreparedStatement pst3=con.prepareStatement("select publisher_id from publishers where publisher = "+ "'" + request.getParameter("pub")+"'");
    ResultSet rst3=pst3.executeQuery();
    ResultSetMetaData rsmd3=rst3.getMetaData();
    int nnn=rsmd3.getColumnCount();
    while(rst3.next())
    pid=rst3.getInt(1);
    rst3.close();
    //str4=request.getParameter("pub");
    try
    if(request.getParameter("bookable").equals("true"))
    str5="1";
    }catch(Exception e)
    str5="0";
    //str5=request.getParameter("bookable"");
    %><input name="med_edit" value="Save Changes" type="submit"><br></form>
    <%
    //out.println("<h2>2"+str1+"</h2>");
    PreparedStatement pstmt3=con.prepareStatement("UPDATE media set media_code="+str1+",target_gender_id="+mgid+",target_age="+tage+",publisher_id="+pid+" WHERE media_id="+"'"+request.getParameter("media_id")+"'");
    pstmt3.executeUpdate();
    //ResultSet res=.updateRow();
    //out.println("<h2>3"+str1+"</h2>");
    }catch(Exception e)
    out.println(e);
    finally
    con.close();
    %>
    <%--
    This example uses JSTL, uncomment the taglib directive above.
    To test, display the page like this: index.jsp?sayHello=true&name=Murphy
    --%>
    <%--
    <c:if test="${param.sayHello}">
    <!-- Let's welcome the user ${param.name} -->
    Hello ${param.name}!
    </c:if>
    --%>
    </body>
    </html>
    //This is another jsp which i replaced for edit_search.jsp.Functionality is same.And also giving the same result.But this is some what clear than edit_search.jsp.
    ****************************test.jsp******************************
    <%@page contentType="text/html"%>
    <%@page pageEncoding="UTF-8"%>
    <%--
    The taglib directive below imports the JSTL library. If you uncomment it,
    you must also add the JSTL library to the project. The Add Library... action
    on Libraries node in Projects view can be used to add the JSTL 1.1 library.
    --%>
    <%--
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    --%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
    </head>
    <body>
    <%@ page import="java.sql.*" %>
    <% Connection con=null;%>
    <% String str1=null;
    String str2=null;
    String str3=null;
    String mgid=null;
    String tage=null;
    String pid=null;
    %>
    <%
    try
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    con = DriverManager.getConnection("jdbc:mysql://silverbullet:3306/elmophish", "sirisha", "gametel123");
    PreparedStatement pstmt=con.prepareStatement("SELECT media_name,media_code,media_type,media_gender,target_age,publisher,is_bookable FROM media m INNER JOIN media_types met ON m.media_type_id = met.media_type_id INNER JOIN media_genders meg ON m.target_gender_id = meg.media_gender_id LEFT JOIN publishers pubs ON m.publisher_id = pubs.publisher_id where media_id=" + "'"+request.getParameter("media_id")+"'");
    ResultSet rs=pstmt.executeQuery();
    while(rs.next()){
    %>
    <form method="post" action="">
    <label>Name</label> <%=rs.getString("media_name")%><br>
    <label>Code</label> <textarea cols="20" rows="1"name="med_code"><%=rs.getString("media_code")%></textarea><br>
    <label>Type</label> <%=rs.getString("media_type")%><br>
    <label>Target Gender</label>&nbsp
    <% PreparedStatement pstmt1=con.prepareStatement("SELECT media_gender FROM media_genders");
    ResultSet rst1=pstmt1.executeQuery();
    %>
    <select name="tar_gen">
    <%
    while(rst1.next())
    %>
    <option><%=rst1.getString("media_gender")%></option>
    <%
    %>
    </select><br>
    <label>Target Age</label> <textarea cols="20" rows="1" name="med_age"><%=rs.getString("target_age")%></textarea><br>
    <label>Publisher</label> 
    <%
    PreparedStatement pstmt2=con.prepareStatement("SELECT publisher FROM publishers");
    ResultSet rst2=pstmt2.executeQuery();
    %>
    <select name="pub">
    <%
    while(rst2.next())
    %>
    <option><%=rst2.getString("publisher")%></option>
    <%
    %>
    </select><br>
    <label>Bookable</label> 
    <input type="checkbox">
    <%
    if (rs.getString("is_bookable").equals("1"))
    %>
    <checkbox maxlength="20" <checked></checkbox>
    <%
    else
    %>
    <checkbox maxlength="20" <unchecked></checkbox>
    <%
    str1=request.getParameter("med_code");
    PreparedStatement pstmt3=con.prepareStatement("select media_gender_id from media_genders where media_gender = "+ "'" + request.getParameter("med_gen") +"'");
    ResultSet rst3=pstmt3.executeQuery();
    while(rst3.next()){
    mgid=rst3.getString("media_gender_id");
    rst3.close();
    try
    tage=request.getParameter("med_age");
    catch(NumberFormatException e){}
    PreparedStatement pstmt4=con.prepareStatement("select publisher_id from publishers where publisher = "+ "'" + request.getParameter("pub")+"'");
    ResultSet rst4=pstmt4.executeQuery();
    while(rst4.next()){
    pid=rst4.getString("publisher_id");
    rst4.close();
    try
    if(request.getParameter("bookable").equals("true"))
    str3="1";
    catch(Exception e)
    str3="0";
    %>
    <input type="submit" value="Save Changes"><br></form>
    <%
    PreparedStatement pstmt5=con.prepareStatement("UPDATE media set media_code="+str1+",target_gender_id="+mgid+",target_age="+tage+",publisher_id="+pid+",is_Bookable="+str3+" WHERE media_id="+"'"+request.getParameter("media_id")+"'");
    pstmt5.executeUpdate();
    out.println("123"+"media_code"+str1+" gender"+mgid+"....age.."+tage+"publisher_id="+pid+" is_Bookable="+str3);
    catch(Exception e)
    out.println("ttttttttttt");
    out.println(e);
    finally
    con.close();
    %>
    <%--
    This example uses JSTL, uncomment the taglib directive above.
    To test, display the page like this: index.jsp?sayHello=true&name=Murphy
    --%>
    <%--
    <c:if test="${param.sayHello}">
    <!-- Let's welcome the user ${param.name} -->
    Hello ${param.name}!
    </c:if>
    --%>
    </body>
    </html>
    *********************************************************************

    I want to know or How to connect Mysql
    with JSP or JSF any other software isavailable?
    please help me.....First you need to find 25 m of a CatV cable and...The DB files need to be located on the ninth device of a SCSI Daisy Chain with the total SCSI cable length being over 150 m (and the devices (and cables) need to be mix of Differential and Non-Differential).
    Edit: And forget the terminator, who needs it?

  • JSP with MYSQL on linux and windows2k

    I am using a linux box as a web server with tomcat and mysql. I aslo have a mirror on a Win2k machine running the same environment.
    I have a jsp file that uses a bean to update the database and it works on the win2k environment but not linux.
    In windows I see error messages in the tomcat console, how do I see these message on linux?
    Thank you,
    Paul.

    Did you check ALL of the files?
    There are files named "localhost_log.TODAYSDATE.txt", there are files named "catalina_log.TODAYSDATE.txt", and there's a file called "catalina.out".
    "catalina.out" appears to contain information very similar to the DOS output screen on the Windows platform.
    If those files don't have what you're looking for, then you'll have to get help from someone with more expertise than myself!

  • Connectivity with MySQL in Windows

    How can I connect JSP with MySQL in Windows?
              I Tried out the following code but It did not work
              Class.forName("org.gjt.mm.mysql.Driver");
              Connection cn = DriverManager.getConnection("jdbc:mysql:///test");
              

    I think you missed the IP address for your MySQL server machine.
              If it's on the same computer, try this:
              jdbc:mysql://localhost/test
              "John Jacob" <[email protected]> wrote in message
              news:[email protected]..
              > How can I connect JSP with MySQL in Windows?
              > I Tried out the following code but It did not work
              >
              > Class.forName("org.gjt.mm.mysql.Driver");
              > Connection cn = DriverManager.getConnection("jdbc:mysql:///test");
              

  • PleaseHelp on jsp and Mysql connectivity and a lot of exception errors

    Hi,
    I am Trying to connect a JSP page with Mysql database. I am having a lot of probelms. After having a lot of problems in connecting the JSp with Mysql. Intilally it was giving me the exception error that " NO appropriate driver was found. After modifying the URl it was fine. Now It is giving the Following errors.
    servlet.ServletException: Communication link failure: java.io.IOException, underlying cause: Unexpected end of input stream ** BEGIN NESTED EXCEPTION ** java.io.IOException MESSAGE: Unexpected end of input stream
    In a window before loading the Explorer page it is giving the following error that The port 8081 is already in use and i should expand to other ports. Noraml JSP Files which used to work before are also not working .
    Internal Tomcat JWSDP is alos not working. If i try to start the server it says that port 8081 is already in USe . A java.net.connection exception is also occuring. The normal JSP files are also not working. What is Happening. I am also giving the code i have writted. PLease tellme why so many exception errors are occuring.
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:8081/mis_project", "root", " ");
    Statement stmt = con.createStatement();
    ResultSet rs = stmt.executeQuery("Select study_semester FROM Semester");
    while(rs.next()) {
    %>
    <option value="<%= rs.getString("Study_Semester") %>">
    </option>
    <% }
    if(rs!=null) rs.close();
    if(stmt!=null) stmt.close();
    if(con!=null) con.close();
    I am trying to connect to Mysql and automatocally populate a field in a Form in later JSp pages i intend to record the data entered in these fields into other tables.

    <%
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/myDB?user=username&password=mypass");
    Statement stmt = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY);
    String cat = "";
              try{
              cat = request.getParameter("category");
              }catch(NullPointerException npe){}
              ResultSet rs = stmt.executeQuery("SELECT id,fullname FROM users WHERE category LIKE '%motor%' AND subcategory like '%"+cat+"%'");
         %>
    This piece gets a category parameter from a form post and uses it to search for a specific category in a database table. I think maybe u need to download JConnector from mysql site and unzip it to the classes folder of your WEB-INF in Tomcat server...... i hope this helps a bit

  • JSP, EJB in Jboss 4 with mySQL database. Error in connecting to database

    Hi, i using JBoss 4-0-1 with jsp and mySQL database. I get this example from a book using stateless session beans. However i modify it so it can connect to mySQL database.
    This is my code for jsp.
    <%@ page import="asg.MusicEJB.*,
    java.util.*,
    javax.naming.Context,
    javax.naming.InitialContext,
    javax.rmi.PortableRemoteObject" errorPage="error.jsp" %>
    <%--
         The following 3 variables appear in a JSP declaration.
         They appear outside the generated _jspService() method,
         which gives them class scope.
         Since we want to initialize our Music EJB object once
         and read the Music Collection database to get the
         recording titles once, we place this code inside
         method jspInit().
         The EJB business method getMusicList()
         returns a collection of RecordingVO objects which we
         store in ArrayList albums.
    --%>
    <%!
         MusicHome musicHome;
         Music mymusic;
         ArrayList albums;
         Properties properties=new Properties();
         public void jspInit() {
                   properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
                   properties.put(Context.PROVIDER_URL, "localhost:3306");
                   System.out.println("............................in properties");
              try {
                   //Context initial = new InitialContext();
                   InitialContext jndiContext = new InitialContext(properties);
                   //Object ref  = jndiContext.lookup("MusicEJB");
                   Object objref = jndiContext.lookup("java:comp/env/ejb/EJBMusic");
                   musicHome = (MusicHome)PortableRemoteObject.narrow(objref, MusicHome.class);
                   mymusic = musicHome.create();
                   albums = mymusic.getMusicList();
                   System.out.println(".............................in line 64");
              } catch (Exception ex) {
                   System.out.println("Unexpected Exception............: " +
                             ex.getMessage());
                   ex.printStackTrace();
    %>
    <%--
         The following scriptlet accesses the implicit
         request object to obtain the current URL
         and saves it to the session object for later retrieval. 
         It also saves variable mymusic, so we can
         make remote calls to our Music EJB, and the collection of
         RecordingVO objects.  These variables will all be available
         to other pages within the session.
    --%>
    <%
         String requestURI = request.getRequestURI();
         session.putValue("url", requestURI);
         session.putValue("mymusic", mymusic);
         session.putValue("albums", albums);
    %>
    <html>
    <head>
    <title>Music Collection Database Using EJB & JSP Version 9.7</title>
    </head>
    <body bgcolor=white>
    <h1><b><center>Music Collection Database Using EJB & JSP</center></b></h1>
    <hr>
    <p>
    There are <%= albums.size() %> recordings.
    <form method="post" action="musicPost.jsp">
    <p>
    Select Music Recording:
    <select name="TITLE">
    <%
         // Generate html <option> elements with the recording
         // titles stored in each RecordingVO element.
         // Obtain the current title from the session object
         // (this will be null the first time).
         String title;
         String currentTitle = (String)session.getValue("curTitle");
         if (currentTitle == null) currentTitle = "";
         RecordingVO r;
         Iterator i = albums.iterator();
         while (i.hasNext()) {
              r = (RecordingVO)i.next();
              title = r.getTitle();
              if (title.equals(currentTitle)) {
                   out.println("<option selected>" + title + "</option>");
              else {
                   out.println("<option>" + title + "</option>");
    %>
    </select><p><p>
    <%--
         Provide a "View Tracks" button to submit
         the requested title to page musicPost.jsp
    --%>
    <input TYPE="submit" NAME="View" VALUE="View Tracks">
    </form>
    </body>
    </html>Message was edited by:
    chongming

    This is the deployment descriptor for the .ear file.
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE application PUBLIC '-//Sun Microsystems, Inc.//DTD J2EE Application 1.3//EN' 'http://java.sun.com/dtd/application_1_3.dtd'>
    <application>
      <display-name>MusicDAOApp</display-name>
      <description>Application description</description>
      <module>
        <web>
          <web-uri>war-ic.war</web-uri>
          <context-root>music</context-root>
        </web>
      </module>
      <module>
        <ejb>ejb-jar-ic.jar</ejb>
      </module>
    <!--
      <module>
        <java>app-client-ic.jar</java>
      </module>
    -->
    </application>
    And this is the deployment for the ejb class files:
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE ejb-jar PUBLIC '-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN' 'http://java.sun.com/dtd/ejb-jar_2_0.dtd'>
    <ejb-jar>
      <display-name>MusicEJB</display-name>
      <enterprise-beans>
        <session>
          <display-name>MusicEJB</display-name>
          <ejb-name>MusicEJB</ejb-name>
          <home>asg.MusicEJB.MusicHome</home>
          <remote>asg.MusicEJB.Music</remote>
          <ejb-class>asg.MusicEJB.MusicBean</ejb-class>
          <session-type>Stateless</session-type>
          <transaction-type>Bean</transaction-type>
          <env-entry>
            <env-entry-name>MusicDAOClass</env-entry-name>
            <env-entry-type>java.lang.String</env-entry-type>
            <env-entry-value>asg.MusicEJB.MusicDAOCloudscape</env-entry-value>
          </env-entry>
         <env-entry>
         <env-entry-name>dbUrl</env-entry-name>
            <env-entry-type>java.lang.String</env-entry-type>
            <env-entry-value>jdbc:mysql://localhost/music</env-entry-value>
          </env-entry>
          <env-entry>
            <env-entry-name>dbUserName</env-entry-name>
            <env-entry-type>java.lang.String</env-entry-type>
            <env-entry-value>chongming</env-entry-value>
          </env-entry>
          <env-entry>
            <env-entry-name>dbPassword</env-entry-name>
            <env-entry-type>java.lang.String</env-entry-type>
            <env-entry-value>kcm82</env-entry-value>
         </env-entry>
          <security-identity>
            <description></description>
            <use-caller-identity></use-caller-identity>
          </security-identity>
        </session>
      </enterprise-beans>
    </ejb-jar>I can combine the jar and war files into a ear file. deploying is alright without any errors.
    However when i run the jsp, it prompt this error:
    You Have Encountered an Error
    Stack Trace
    java.lang.NullPointerException
         at org.apache.jsp.musicGet_jsp._jspService(org.apache.jsp.musicGet_jsp:111)
         at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
         at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:322)
         at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
         at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
         at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:81)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
         at org.jboss.web.tomcat.security.CustomPrincipalValve.invoke(CustomPrincipalValve.java:39)
         at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:159)
         at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:59)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
         at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
         at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:856)
         at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:744)
         at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
         at org.apache.tomcat.util.net.MasterSlaveWorkerThread.run(MasterSlaveWorkerThread.java:112)
         at java.lang.Thread.run(Thread.java:595)
    How to i solve the error? I look at he catch results in the command prompt of JBoss , i found that when running, the code will be caught by the exception and display this:int.java:527)
    at org.apache.tomcat.util.net.MasterSlaveWorkerThread.run(MasterSlaveWor
    kerThread.java:112)
    at java.lang.Thread.run(Thread.java:595)
    13:55:21,375 INFO [STDOUT] Unexpected Exception............: EJBException:; nes
    ted exception is:
    javax.ejb.EJBException: getMusicList: SQLException during DB Connection:
    The url cannot be null
    13:55:21,375 INFO [STDOUT] java.rmi.ServerException: EJBException:; nested exce
    ption is:
    javax.ejb.EJBException: getMusicList: SQLException during DB Connection:
    The url cannot be null 13:55:21,375 INFO[STDOUT] at org.jboss.ejb.plugins.LogInterceptor.handleException(LogInterceptor.java:352)
    13:55:21,375 INFO [STDOUT] at org.jboss.ejb.plugins.LogInterceptor.invoke(LogInterceptor.java:196)
    What can i do to solve the problem? please helpMessage was edited by:
    chongming
    Message was edited by:
    chongming
    Message was edited by:
    chongming

  • How to create table with jsp in mysql

    Hi, every one,
    I just want to know how to create a table with jsp in mysql, please.
    Thanks in advance

    I have got the same question. I tried to pass sql "Create table" statement, but the servlet engine (tomcat4) threw an error "could not manipulet statement.execute". It works for normal SQL select statement.
    Anyone got the same problem ? or got a solution for this ? someone told me that PHP can do it, but just want to get it works with JSP.

  • Can' t connect Java with MySQL

    My goal is to connect Java with MySQL. I found many solutions on Internet, but I always get the same mistake:
    SQLException: No suitable driver
    SQLState: 08001
    VendorError: 0MySQL works fine alone or with php.Only thing left me to think is that the installed versions are not compatible for this mysql-connector-java-5.0.4
    I don't believe that could be a reason.
    Installed versions are:
    Apache Tomcat 5.5.20 Server
    Apache HTTP Server 2.2.4
    PHP 5.2.0
    MySQL 5.2
    jre 1.5.0_11
    jdk1.5.0_11
    Apache Tomacat JK2 connector Version: 1.2.20 File Name: mod_jk-apache-2.2.3.so
    mysql-connector-java-5.0.4
    I also set connector in class path: C:\mysql-connector-java-5.0.4;C:\mysql-connector-java-5.0.4\mysql-connector-java-5.0.4-bin.jar;C:\mysql-connector-java-5.0.4\src\com\mysql\jdbc
    For installation I used manulas from:
    http://apacheguide.org/jsp.php
    http://doc.51windows.net/mysql/?url=/MySQL/ch23s03.html
    Here is also a test code in java:
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
       public class Connect
           public static void main (String[] args)
               Connection conn = null;
               try {
        conn =
           DriverManager.getConnection("jdbc:mysql://localhost/first_test" +
                                       "user=monty&password=greatsqldb");
        // Do something with the Connection
    } catch (SQLException ex) {
        // handle any errors
        System.out.println("SQLException: " + ex.getMessage());
        System.out.println("SQLState: " + ex.getSQLState());
        System.out.println("VendorError: " + ex.getErrorCode());
       }i'm desperate, please help or tell me someone who'll know the answer.
    Thank You in advance

    hey buddy .. it seems yr code is wrong .. in getconnection () method u should also specify the port ,which u r not doing ...
    the default port for MySQL is 3306 ... see below i am giving you a sample code ... its working fine .. and dont forget to put the MySQL driver jar path in to classpath and also copy the jar into common/lib folder of your tomcat ....
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    public class MySQLConnectionTest {
         public static void main(String[] args) {
    new MySQLConnectionTest().connTest();
    public void connTest() {
              String tableName = "portfolio"; //change as per setting
              String hostName = "10.81.9.39"; // please change for the target database ip or hostname
              String dbPort = "3306"; //change if not using the default
              String dbName = "tradingsystem"; //change as per the given DB name
              String username = "root"; //change as per setting
              String password = "password"; //change as per setting
              System.out.println("before try");
              Double data=0.0;
         Double data1=0.0;
              try {
    Class.forName("org.gjt.mm.mysql.Driver");
                   System.out.println("before driver manager");
    Connection conn = DriverManager.getConnection("jdbc:mysql://"+hostName+":"+dbPort+"/"+dbName, username, password);
    String query1 = "select * from "+tableName+" where User_id='trader1' and Stock_Type='Equity'";
    System.out.println("quesry1="+query1);
    Statement stmt = conn.createStatement();
    ResultSet rs1 = stmt.executeQuery(query1);
    while(rs1.next())
         System.out.println("hiiiiii for rs1");
         System.out.println(rs1);
         Quantity=(Integer)rs1.getObject(5);
         MarketPrice=(Double) rs1.getObject(8);
         data=Quantity*MarketPrice;
         data1+=data;
         System.out.println("data1="+data1);
         i=0;
    rs1.close();
    stmt.close();
    conn.close();
    } catch (ClassNotFoundException e) {
    e.printStackTrace(System.err);
    } catch (SQLException e) {
    e.printStackTrace(System.err);
    i hope it will work for u...
    cheers,

  • Java with MYSQL in Linux

    i am using JSP in Linux Platform. when i connected to mysql with mysql driver for odbc by using the following code,
    import java.sql.*;
    public class TestMysql
    public static void main(String args[]) {
    try {
              Connection con;
              String connStr = "jdbc:mysql://localhost/test?user=root&password=mysql";
              Class.forName( "com.mysql.jdbc.Driver" ).newInstance();
              System.out.println("OK");
              con = DriverManager.getConnection( connStr );
              System.out.println("Again OK");
    catch( Exception x )
    x.printStackTrace();
    i got the following exception
    OK
    java.sql.SQLException: Error during query: Unexpected Exception: java.io.CharConversionException message given: null
    Nested Stack Trace:
    ** BEGIN NESTED EXCEPTION **
    java.io.CharConversionException
    STACKTRACE:
    java.io.CharConversionException
    at gnu.gcj.convert.Input_iconv.read(char[], int, int) (/usr/lib/libgcj.so.5.0.0)
    at java.lang.String.init(byte[], int, int, java.lang.String) (/usr/lib/libgcj.so.5.0.0)
    at java.lang.String.String(byte[], int, int, java.lang.String) (/usr/lib/libgcj.so.5.0.0)
    at com.mysql.jdbc.SingleByteCharsetConverter.SingleByteCharsetConverter(java.lang.String) (Unknown Source)
    at com.mysql.jdbc.SingleByteCharsetConverter.initCharset(java.lang.String) (Unknown Source)
    at com.mysql.jdbc.SingleByteCharsetConverter.getInstance(java.lang.String, com.mysql.jdbc.Connection) (Unknown Source)
    at com.mysql.jdbc.Connection.getCharsetConverter(java.lang.String) (Unknown Source)
    at com.mysql.jdbc.StringUtils.getBytes(java.lang.String, java.lang.String, java.lang.String, boolean, com.mysql.jdbc.Connection) (Unknown Source)
    at com.mysql.jdbc.Buffer.writeStringNoNull(java.lang.String, java.lang.String, java.lang.String, boolean, com.mysql.jdbc.Connection) (Unknown Source)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(com.mysql.jdbc.Statement, java.lang.String, java.lang.String, com.mysql.jdbc.Buffer, int, com.mysql.jdbc.Connection, int, int, boolean, java.lang.String, boolean) (Unknown Source)
    at com.mysql.jdbc.Connection.execSQL(com.mysql.jdbc.Statement, java.lang.String, int, com.mysql.jdbc.Buffer, int, int, boolean, java.lang.String, boolean, boolean) (Unknown Source)
    at com.mysql.jdbc.Connection.configureClientCharacterSet() (Unknown Source)
    at com.mysql.jdbc.Connection.initializePropsFromServer() (Unknown Source)
    at com.mysql.jdbc.Connection.createNewIO(boolean) (Unknown Source)
    at com.mysql.jdbc.Connection.Connection(java.lang.String, int, java.util.Properties, java.lang.String, java.lang.String) (Unknown Source)
    at com.mysql.jdbc.NonRegisteringDriver.connect(java.lang.String, java.util.Properties) (Unknown Source)
    at java.sql.DriverManager.getConnection(java.lang.String, java.util.Properties) (/usr/lib/libgcj.so.5.0.0)
    at java.sql.DriverManager.getConnection(java.lang.String) (/usr/lib/libgcj.so.5.0.0)
    at TestMysql.main(java.lang.String[]) (Unknown Source)
    ** END NESTED EXCEPTION **
    at com.mysql.jdbc.Connection.execSQL(com.mysql.jdbc.Statement, java.lang.String, int, com.mysql.jdbc.Buffer, int, int, boolean, java.lang.String, boolean, boolean) (Unknown Source)
    at com.mysql.jdbc.Connection.configureClientCharacterSet() (Unknown Source)
    at com.mysql.jdbc.Connection.initializePropsFromServer() (Unknown Source)
    at com.mysql.jdbc.Connection.createNewIO(boolean) (Unknown Source)
    at com.mysql.jdbc.Connection.Connection(java.lang.String, int, java.util.Properties, java.lang.String, java.lang.String) (Unknown Source)
    at com.mysql.jdbc.NonRegisteringDriver.connect(java.lang.String, java.util.Properties) (Unknown Source)
    at java.sql.DriverManager.getConnection(java.lang.String, java.util.Properties) (/usr/lib/libgcj.so.5.0.0)
    at java.sql.DriverManager.getConnection(java.lang.String) (/usr/lib/libgcj.so.5.0.0)
    at TestMysql.main(java.lang.String[]) (Unknown Source)
    i have the database, hello.
    The same code works well in Windows, But in Linux, the above exception.
    By using the username root and password mysql , i can connect to mysql directly from the mysql prompt.
    Pls help me..
    I have already put the query 'access denied problem in Mysql' some day before. from the reply, i made some changes in user table(ie. set the password for [email protected].).After this change, this new Exception came..
    The structure of my mysql.user table is
    #     host                         user          password
    1     localhost                    root          68d4f47c49a579c9
    2     localhost.localdomain          root          68d4f47c49a579c9
    3     localhost.localdomain          
    4     localhost          
    Pls help me.
    Edited by: SUMESHBABU_R on Sep 30, 2007 11:36 PM

    Well, at least the trace tells me that this issue is to be tracked back to the core of the MySQL JDBC driver and the Linux's implementation of JVM. It might be worth the effort to post this issue at their website/forum/issuetracker. It might also be worth the effort to tryout the newer MySQL JDBC driver 5.1, as it is written specific for JDK 6.0 (while MySQL JDBC driver 5.0 is targeted at JDK 5.0).

  • ExecuteQuery() error with MySQL

    I have already followed all the steps recommended by OTN to create a connection with MySQL (most up-to-date files) in JDeveloper 10g. It works fine except when I try to find a view and execute a query using an Application Module in a jsp:
    ApplicationModule appMod = appMod.getGenericAppMod();
    ViewObject voTabEmployee = appMod.findViewObject("TabEmployee");
    voTabEmployee.executeQuery();
    It works ok when connected to Oracle DB but it raises the following exception when I move Business Components to a MySQL connection, exactly as recommended:
    java.lang.ClassCastException: com.mysql.jdbc.ServerPreparedStatement
    Any help would be highly appreciated.
    Marcio

    Hi Marcio
    The ApplicationModule that you create in your source (utilApp.java) is created using the default configuration that uses the OracleSQLBuilder as the default SQLBuilder (configured to work with Oracle Databases). Thus, when you use MySQL or any other database (and I confirmed this using SQLServer), a ClassCastException is thrown.
    Instead of using the following lines:
    Context ic = new InitialContext(env);
    String theAMDefName = "mysysjcom.MySysJComModule";
    ApplicationModuleHome home = (ApplicationModuleHome) ic.lookup(theAMDefName);
    ApplicationModule appMod = home.create();
    appMod.getTransaction().connectToDataSource(null, "jdbc/MYSYSJCOMCoreDS", false);
    can you use the following lines:?
    Context ic = new InitialContext(env);
    String theAMDefName = "mysysjcom.MySysJComModule";
    ApplicationModule appMod = Configuration.createRootApplicationModule(theAMDefName, <config_name>);
    ic.lookup(theAMDefName);
    I got your sample working with the above change
    This will ensure that you are using the same configuration that has the SQLBuilder correctly set to your Database type
    Thanks
    Prasanth

  • Date Problem in Java with MySql

    Hello
    I am using Java with Mysql.I want to enter date in some in my format(YYYY:MM:DD:HH:MM:SS), this thing i have convert using format class and format class return date in String and iwwnat to insert this value in MySQL Table,So i want to know how can i convert String value in Date for Mysql is their inbuild function for converting string into date in mysql.
    Regards
    Anupam S

    Use PreparedStatement and SimpleDateFormat classes
    http://onesearch.sun.com/search/onesearch/index.jsp?qt=%2BPreparedStatement+%2BSimpleDateFormat+&qp=siteforumid%3Ajava48&chooseCat=allJava&col=developer-forums&site=dev

Maybe you are looking for

  • Mavericks 10.9.1-Problem with finder not showing peripheral hardware

    After upgrading to Mavericks (10.9.1) my Finder doesn't show new hardware in Devices. For example, Finder not showing iPod when i plug into the keyboard's usb. i have other examples  of the same problem, such as trying to find a hard drive detached f

  • TLFTextField or TLF, which is better to use in CS5?

    Hi, I have been developing content using TLF with CS4 and in Flash Builder. Recently when I switched to CS5, there was this cool TLFTextField. So now I wonder, TLFTextField or TLF, which is better to use in CS5? Almost all of my text will be dynamica

  • PDF exporting issues

    Last night I was able to export pdf's fine, but this morning not so much. I go to export them, and I can see in the background tasks that it is doing so. I check finder and can see the file being made (at 0 bytes), and once the background task finish

  • Is their a fix for photoshop elements 11 move tool? Not working with Yosemite OS upgrade.

    Is their a fix for photoshop elements 11 move tool? Not working with Yosemite OS upgrade.

  • To get  HOD for the employees(HR-ABAP)

    Hi Experets, i am new in  abap hr please suggest me  how to get hod of an employee and trying to do with bellow codes, kindly suggest me. select single ORGEH from pa0001 into lv_orgeh where pernr = employeenumber