I have the following Java class:
package web;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
public class HelloWorld extends HttpServlet {
public void doPost(HttpServletRequest request,HttpServletResponse response)throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Student Name<br>");
try{
Connection conn=null;
String url = "jdbc:mysql://localhost/test";
PreparedStatement pre=null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn=DriverManager.getConnection(url,"root","3324911");
out.println("Database connected");
pre = conn.prepareStatement("Insert INTO countries(COUNTRY,COUNTRY_ISO_CODE,REGION) VALUES (?,?,?)");
pre.setString(1,"USA");
pre.setString(2,"US");
pre.setString(3,"North America");
pre.executeUpdate();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
For whatever reason, after I deploy this class in Tomcat, the program could only reach the line
Class.forName("com.mysql.jdbc.Driver").newInstance();
It will fail after it gets to line:
conn=DriverManager.getConnection(url,"root","3324911");
and this try/catch block is working as a separate method, I took it from a main method from another class, and it is working properly.
I am not sure where I messed up when I plug this try/catch block here in Tomcat.
Any help is appreciated, thanks!
Is the JDBC driver configured in the path or copied into the lib directory (i.e. $CATALINA_HOME/lib or web-inf/lib)?
Also, it would be better if you use a connection pool – tomcat comes with one which is a better approach than spawning your own DB connections.
Also, it might be better if you clean up your DB related resources (unless you just left it out from the code above for simplicity).
Hope this helps.
Yes, I agree with the other responders – getting more detailed error logging might be the preferred route.