| Author |
Servlet & JDBC
|
Siddhartha Mukherjee
Greenhorn
Joined: Jan 27, 2005
Posts: 8
|
|
I tried to connect a MySQL database using the following code in a standalone application, which was successful: import java.sql.*; public class testDB { public static void main(String arg[]) { try{ Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql:///website","root",""); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("select * from InternalConfHall"); while(rs.next()) {String s = rs.getString(1); System.out.println(s); } } catch(Exception e) {} } } //------------------------------------------------ But the same code of the data base connection block when used in a servlet code it has thrown an exception com.mysql.jdbc.Driver. So please help me to connect to the same mysql database using servlet code.The code I'v used is given below : import java.io.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; public class seeAvailability extends HttpServlet { public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); try { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql:///website","root",""); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("select * from InternalConfHall"); while(rs.next()) {String s = rs.getString(1); System.out.println(s); } } catch(Exception e) { out.println("Error:" + e.getMessage()); } DO GET WILL INTERNALLY CALL DO POST METHOD public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { doPost(req,res); //CALL DO POST METHOD, DEFINED ABOVE } } //-------------------------------------------------------------------- Please help me Thanks In Advance
|
 |
Ben Souther
Sheriff
Joined: Dec 11, 2004
Posts: 13410
|
|
You'll need to put your driver where your app can find it. Check your server's documentation to see how this is done.
|
Java API J2EE API Servlet Spec JSP Spec How to ask a question... Simple Servlet Examples jsonf
|
 |
Murasoli Maran
Ranch Hand
Joined: Jun 08, 2003
Posts: 193
|
|
Put the driver jar file in WEB-INF/lib directory. MM
|
 |
Adeel Ansari
Ranch Hand
Joined: Aug 15, 2004
Posts: 2874
|
|
And please dont do Database manipulation stuff in your servlet. thanks.
|
 |
Jeroen Wenting
Ranch Hand
Joined: Oct 12, 2000
Posts: 5093
|
|
|
For experiments it's fine but indeed for real life systems you should consider abstracting away the database access code to a separate set of classes (and using connection pooling).
|
42
|
 |
prad gop
Greenhorn
Joined: Oct 18, 2004
Posts: 2
|
|
You can put your corresponding jar file containing the driver in the WEB-INF/lib and try with Class.forName("com.mysql.jdbc.Driver").newInstance();
|
 |
 |
|
|
subject: Servlet & JDBC
|
|
|