Naga Vemprala Naga Vemprala - 28 days ago 4
Java Question

JDBC getConnection is not working on Tomcat server. But it is running as a Java Application

I have the code as below, which worked perfectly fine when I ran it as a Java Application:

package com.LearnersLingoo.WebContent;


// Consider all the necessary imports are taken care

public class VerifyUser {

public VerifyUser(){

}
boolean userExist(String userName, String userPassword){
return true;
}

public static void main(String[] args) throws SQLException {
Connection myConn = null;
Statement myStmt = null;
ResultSet myRes = null;

try{
myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "student", null);
System.out.println("Connection Successful");

myStmt = myConn.createStatement();

int rowsAffected = myStmt.executeUpdate("insert into learners" +
"(ID, userName, FirstName, LastName, Password)" +
"values" +
"(11001, 'Test', 'testUser', 'UserLastN', 'password')");

System.out.println("Rows inserted: " + rowsAffected);
}
catch (Exception e){
e.printStackTrace();
}
}
}


The console message is as below:

Connection Successful
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '11001' for key 'PRIMARY'


Here anyway the user is already present, so atleast the connection is successful.

When I have the similar code run as a Servlet I am getting

Connnnection not successfuljava.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/test


I have gone through other similar questions on this topic which suggested me to add class.forname( com.mysql.jdbc.driver ) But it did not help

@WebServlet
public class HomePage extends HttpServlet {
private static final long serialVersionUID = 1L;
private Connection connection;
/**
* @see HttpServlet#HttpServlet()
*/
public HomePage() {
super();
// TODO Auto-generated constructor stub
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
public void init(){
try {
// Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "student", null);
System.out.println("Connection Successful");

} catch (SQLException e) {
System.out.println("Connnnection not successful");
e.printStackTrace();
}

}


Kindly help me on how to add the JDBC jar on Tomcat server. I am running Tomcat server for my web application in Eclipse installed on Mac.

Updated full stack trace:

java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/test
at java.sql.DriverManager.getConnection(DriverManager.java:689)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at com.LearnersLingoo.WebContent.HomePage.init(HomePage.java:37)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1183)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1099)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:779)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:133)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
Connnnection not successful
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:784)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)

Answer

I am able to resolve this issue by doing this: I added the MySQL JDBC jar file to Tomcat Server using Tomcat Server "Open Launch Configuration" --> ClassPath. This resolved the issue. Could you please tell me if this is the correct way to resolve the issue ? So in total, I added the JDBC driver at two places. 1) To the web application classpath 2) to the Tomcat server classpath

You don't need to add the JAR in both the places, the best practice is to make it available to the respective web application's classpath (i.e., WEB-INF/lib).

Also, rather than adding it manually, ensure that your build tool (Maven, Gradle, etc) packages all required dependencies for you to the project's lib folder. So, when you deploy the project into the server, the JAR will be available in the respective lib folder.