473,396 Members | 1,827 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Can't establish connection between Servlet and MySQL

xploreraj
Config.: Apache Tomcat 5.5; MySQL 5.0


Hello,

I am trying to establish a connection between servlet and MySQL database. For this I have compiled my servlet which has table for inputting values into a database table in MySQL.

Here goes the code:

Expand|Select|Wrap|Line Numbers
  1. //Use this table for this program
  2. /*
  3. create table course(id int,
  4. name varchar(20),
  5. ctype varchar(20),
  6. duration varchar(20),
  7. semester int);
  8. */
  9.  
  10.  
  11. import java.io.*;
  12. import javax.servlet.*;
  13. import javax.servlet.http.*;
  14. import java.sql.*;
  15. import java.util.*;
  16.  
  17.  
  18. public class Course1 extends HttpServlet
  19. {
  20. Connection conn=null;
  21. Statement stmt = null;
  22. ResultSet rs;
  23.  
  24. //---------------------------Register Driver-------------------
  25.  
  26. public void init()
  27. {
  28. try
  29. {
  30. String un="root";
  31. String pass="admin";
  32. String url="jdbc:mysql://localhost:3036/BOOKS_DB";
  33. Class.forName("com.mysql.jdbc.Driver").newInstance();
  34. conn =DriverManager.getConnection(url,un,pass); 
  35. System.out.println("Database Connection Established");
  36. }
  37.  catch(Exception e)
  38. {
  39. System.out.println("Sorry failed to connect to the DataBase." +e.getMessage());
  40. }
  41. }
  42.  
  43.  
  44. public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
  45. {
  46. HttpSession session=request.getSession();
  47. response.setContentType("text/html");
  48. PrintWriter out=response.getWriter();
  49.  
  50.  
  51. int y=0;
  52. int x=0;
  53.  
  54. out.println("<html><head><title>Welcome to Institution</title>");
  55.  
  56. //----------------java script---------------------------------
  57.  
  58. out.println("<script>");
  59. out.println("function abc() {");
  60. out.println("if (document.thisform.name.value==0) {");
  61. out.println("alert('Invalid Name');");
  62. out.println("return false; }");
  63. out.println("if (document.thisform.ctype.value==0) {");
  64. out.println("alert('Invalid Type');");
  65. out.println("return false; }");
  66. out.println("if (document.thisform.duration.value==0) {");
  67. out.println("alert('Invalid Duration');");
  68. out.println("return false; }");
  69. out.println("if (document.thisform.semester.value==0) {");
  70. out.println("alert('Invalid Semester');");
  71. out.println("return false; }");
  72. out.println("document.thisform.submit();");
  73. out.println("return false; }");
  74.  
  75. out.println("function setEditMode(id,cname,typ,durt,seme)");
  76. out.println("{");
  77. out.println("document.thisform.hiddenid.value=id;");
  78. out.println("document.thisform.name.value=cname;");
  79. out.println("document.thisform.ctype.value=typ;");
  80. out.println("document.thisform.duration.value=durt;");
  81. out.println("document.thisform.semester.value=seme;");
  82. out.println("document.thisform.hidMode.value='U';");
  83. out.println("}");
  84.  
  85. out.println("function setDelMode()");
  86. out.println("{");
  87. out.println("document.thisform.hidMode.value='D';");
  88. out.println("formDeleteValues('hidSelDel');");
  89. out.println("}");
  90.  
  91. out.println("function formDeleteValues(hidden)");
  92. out.println("{");    
  93. out.println("var selval=\" \" ");
  94. out.println("for(i=0;i<document.forms[0].elements.length;i++)");
  95. out.println("{");
  96. out.println("if(document.forms[0].elements[i].type == \"checkbox\")");
  97. out.println("{");
  98. out.println("if(document.forms[0].elements[i].checked == true) {");
  99. out.println("selval=selval + document.forms[0].elements[i].value + \",\" ;");
  100. out.println("}");
  101. out.println("}");
  102. out.println("}");
  103. out.println("if(selval.length < 1)");
  104. out.println("{");
  105. out.println("alert(\"Please choose records you wish to delete.\");");
  106. out.println("}");
  107. out.println("else");
  108. out.println("{");
  109. out.println("selval=selval.substring(0,selval.length-1);");
  110. out.println("eval(\"document.forms[0].\" +hidden+\".value = '\"+selval+\"'\");");
  111. out.println("document.forms[0].submit(); } }");
  112.  
  113.  
  114.  
  115. out.println("</script></head>");
  116.  
  117. //-------------------------body----------------------------------
  118.  
  119. out.println("<body bgcolor='rgb(255,210,117)'>");
  120. int sem=0,id=0;
  121.  
  122.  
  123. //--------------------Insert---------------------------------------
  124.  
  125. if ("I".equals(request.getParameter("hidMode")) && conn != null)
  126. {
  127.  
  128. String nm=request.getParameter("name");
  129. String ty=request.getParameter("ctype");
  130. String dur=request.getParameter("duration");
  131. String sem1=request.getParameter("semester");
  132. sem=Integer.parseInt(sem1);
  133.  
  134. try
  135. {
  136. if(nm.length() > 1 && ty.length() > 1)
  137. {
  138. stmt = conn.createStatement(); 
  139. String sql=new String();
  140. sql="select max(id) from Course";
  141. rs=stmt.executeQuery(sql);
  142. boolean  b = rs.next();
  143. if(b)
  144. {
  145. x = rs.getInt(1);
  146. }
  147. else
  148. {
  149. x = 0;
  150. }
  151. x=x+1;
  152. id=x;
  153.  
  154. stmt=conn.createStatement();
  155.  
  156. sql="Insert into Course values("+ id +",'"+ nm +"','"+ ty +"','"+ dur +"',"+ sem +")";
  157. System.out.println(sql);
  158. y=stmt.executeUpdate(sql);
  159. }
  160. else
  161. {
  162. out.println("Details cannot be left blank");
  163. }
  164.  
  165. }
  166.  catch(Exception e)
  167. {
  168. out.println("Sorry failed to insert values into the Database table." +e.getMessage());
  169. }
  170.  
  171. }
  172.  
  173. //----------------------------update--------------------------
  174.  
  175. if("U".equals(request.getParameter("hidMode")) && conn != null)
  176. {
  177.  
  178. String nm=request.getParameter("name");
  179. String ty=request.getParameter("ctype");
  180. String dur=request.getParameter("duration");
  181. String sem1=request.getParameter("semester");
  182. sem=Integer.parseInt(sem1);
  183.  
  184.  
  185.  try
  186. {
  187. stmt=conn.createStatement();
  188. String sql4=new String();
  189. sql4="update Course set name='"+ nm +"',ctype='"+ ty + "',duration='"+ dur +"',semester="+ sem +" where id="+ Integer.parseInt(request.getParameter("hiddenid")) +" ";
  190. stmt.executeUpdate(sql4);
  191. }
  192. catch(Exception e)
  193. {
  194. out.println("Sorry failed to update values from the database table." + e.getMessage());
  195. }
  196.  
  197. }
  198.  
  199. //---------------------------Delete-----------------------------
  200.  
  201. if("D".equals(request.getParameter("hidMode")) && conn != null)
  202. {
  203. try
  204. {
  205. stmt=conn.createStatement();
  206. String sql5=new String();
  207. sql5="delete from Course where id IN("+ request.getParameter("hidSelDel") +") ";
  208. System.out.println(sql5);
  209. stmt.executeUpdate(sql5);
  210. }
  211. catch(Exception e)
  212. {
  213. out.println("Sorry failed to delete values from the database table." + e.getMessage());
  214. }
  215.  
  216. }
  217.  
  218.  
  219. //----------------------------html-------------------------------
  220.  
  221. out.println("<form name='thisform' method='get' action='../servlet/Course1'>");
  222.  
  223. out.println("<input type='hidden' name='hidMode' value='I'>");
  224. out.println("<input type='hidden' name='hiddenid'>");
  225. out.println("<input type='hidden' name='hidSelDel'>");
  226.  
  227. out.println("<table align='center' bgcolor='rgb(255,210,117)' width='50%'>");
  228. out.println("<tr>");
  229. out.println("<td>");
  230.  
  231.  
  232. out.println("</td></tr><br><br><br><tr height='200'>");
  233. out.println("<td align='center' colspan='10'>");
  234.  
  235. out.println("<table align='center' bgcolor='rgb(255,210,117)' border='1' bordercolor='maroon' cellpadding='2' cellspacing='0' width='100%'>");
  236. out.println("<tr><td align='left' colspan='2' bgcolor='maroon'>");
  237. out.println("<font color='rgb(255,210,117)' ><b>Course Details</b></font></td></tr>");
  238.  
  239. out.println("<tr><th align='right'>Course Name</th>");
  240. out.println("<td><input type='text' name='name' size='25'></td></tr>");
  241. out.println("<tr><th align='right'>Type</th>");
  242. out.println("<td><input type='text' name='ctype' size='25'></td></tr>");
  243. out.println("<tr><th align='right'>Duration</th>");
  244. out.println("<td><input type='text' name='duration' size='25'></td></tr>");
  245. out.println("<tr><th align='right'>Semesters</th>");
  246. out.println("<td><select name='semester'><option value='1'>Sem1<option value='2'>Sem2<option value='3'>Sem3<option value='4'>Sem4<option value='5'>Sem5<option value='6'>Sem6<option value='7'>Sem7<option value='8'>Sem8</select></td></tr>");
  247.  
  248. out.println("<tr><td colspan='2' align='right'><input type='submit' value='Save' onClick='return abc();'>");
  249. out.println("<input type='reset' value='Reset'></td></tr></table>");
  250. out.println("</td></tr></table>");
  251.  
  252.  
  253. if(conn != null)
  254. {
  255. try
  256. {
  257. stmt=conn.createStatement();
  258. String sql2=new String();
  259.  
  260. sql2="Select * from Course";
  261. ResultSet rs1=stmt.executeQuery(sql2);
  262. out.println("<table align='center' border='1' width='50%' bordercolor='skyblue'>");
  263. out.println("<tr bgcolor='black'>");
  264. out.println("<td width='12%' align='center' ><input type='button' name='cmdDelete' value='Delete' onClick='setDelMode();'></td>");
  265. out.println("<td><font color='#FFFFFF'>Course Name</font></td>");
  266. out.println("<td><font color='#FFFFFF'>Type</font></td>");
  267. out.println("<td><font color='#FFFFFF'>Duration</font></td>");
  268. out.println("<td><font color='#FFFFFF'>Semesters</font></td>");
  269. out.println("</tr>");
  270.  
  271. int ii,s1;
  272. String n1,t1,d1;
  273.  
  274. if(rs1 != null)
  275. {
  276.  while(rs1.next())
  277. {
  278.   out.println("<tr>");
  279.  ii=Integer.parseInt(rs1.getString("id"));  
  280.  n1=rs1.getString("name");
  281.  t1=rs1.getString("ctype");
  282.  d1=rs1.getString("duration");
  283.  s1=Integer.parseInt(rs1.getString("semester"));
  284.  
  285. out.println("<td><input type='checkbox' name='chk"+ii+"' value=" + ii +"></td>");
  286.  
  287. out.println("<td style=\"cursor:pointer\" onMouseDown=\"setEditMode('"+ ii +"','"+ n1 +"','"+ t1 +"','"+ d1 +"','"+ s1 +"');\">" + n1  + "</td>");
  288.  
  289. out.println("<td style=\"cursor:pointer\" onMouseDown=\"setEditMode('"+ ii +"','"+ n1 +"','"+ t1 +"','"+ d1 +"','"+ s1 +"');\">"+ t1 + "</td>");
  290.  
  291. out.println("<td style=\"cursor:pointer\" onMouseDown=\"setEditMode('"+ ii +"','"+ n1 +"','"+ t1 +"','"+ d1 +"','"+ s1 +"');\">"+ d1 + "</td>");
  292.  
  293. out.println("<td style=\"cursor:pointer\" onMouseDown=\"setEditMode('"+ ii +"','"+ n1 +"','"+ t1 +"','"+ d1 +"','"+ s1 +"');\">"+ s1 + "</td>");
  294.  
  295.  out.println("</tr>");
  296. }
  297. }
  298.  
  299.  
  300. }
  301.  catch(Exception e)
  302. {
  303. out.println("Sorry Failed to execute the Query." +e.getMessage());
  304. }
  305.  
  306. }
  307. out.println("</form>");
  308. out.println("</body></html>");
  309. }
  310. }
  311.  
  312.  
  313.  
The servlet is compiled perfectly.

I have the following Environment variables set:

Path: installdir\bin
classpath: C:\MySQL Connector\mysql-connector-java-5.0.4-bin.jar

As in MySQL, I have also created database and table perfectly.

But the problem is that entering values in servlet table and saving it applies no changes to the databases, and also generates no errors.

Please help me fix it.



Regards,
xploreraj
Oct 2 '10 #1
0 1650

Sign in to post your reply or Sign up for a free account.

Similar topics

0
by: Jim the Bad | last post by:
Hi, I wonder if anyone can help me with this. Bog standard SuSE 8.2 Linux install. I have installed mySQL (off the SuSE 8.2 distro CDs). I can connect locally, e.g: bealzebub> mysql -u root...
0
by: TJ | last post by:
Dear Sir/Madam I made one user control using C#(.NET Runtime is 1.1). It is embeded in Internet Explorer Basically, this control is very similiar to FTP client program. So it should be connecte...
1
by: TJ | last post by:
Dear Sir/Madam I made one user control using C#(.NET Runtime is 1.1). It is embeded in Internet Explorer Basically, this control is very similiar to FTP client program. So it should be connecte...
1
by: edmundleungs | last post by:
It is found that a DB is setup for sometime. One day, the user suddenly cannot connect to DB. We found that the case is as follow: 1. User can connect to DB by issuing command db2 connect...
3
by: emrahayanoglu | last post by:
Hello Everyone, I have question about efficient usage of connecting to mysql. Now, i'm using 6 or 7 queries in a page with ajax. In Addition to that, i open connection to mysql for every query....
4
by: d3vkit | last post by:
Okay so I am at a loss here. I have a website that I've previously had no trouble connecting to the mysql DB on. I have an include to a connect file with the relevant connection info, and it was...
0
by: sajithamol | last post by:
What is the method/code using which I can establish connection from Rexx to IMS DB and access the same.
2
by: aidanhaylock | last post by:
Morning, This one is really driving me insane. I am developing a site for a client who doesn't particularly want to move their hosting away from their current provider. The current host are...
6
by: markodilore | last post by:
Hey Guys, you helped me once when I tryied to create a database : "Access denied for user ''@'localhost' ". On my Mac OS 10.4, I had no problem creating database and modifying it from the terminal....
1
by: rhyme2ri2 | last post by:
Hi all, Whenever i try to use 'quote nlst' or 'quote list' in ftp. It gives me this error 425:Can't establish connection. Connection refused'. It works fine when I use ls or dir commands. But I...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.