1

I have spent 2 days trying to figure out why my servlet does not connect to the MySQL database.

I have MySQL installed and working properly and Eclipse.

Whenever I try to establish a connection, I get a ClassNotFoundException for the com.mysql.jdbc.Driver, which is actually properly imported. The connector I'm using is the mysql-connector-java5.1.14 added properly as an external jar, so everything seems fine. Here's my code:

 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String dbUrl="jdbc:mysql://localhost:3306/test"; String username="root"; String password=""; try { Class.forName("com.mysql.jdbc.Driver").newInstance(); conn=DriverManager.getConnection(dbUrl); System.out.println("Connected!"); } catch (SQLException e) { e.printStackTrace(); System.out.println("not connected"); } catch(ClassNotFoundException x){ x.printStackTrace(); } catch(Exception e){ e.printStackTrace(); } } 

Here's part of the stack trace:

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1645) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1491) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:375) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:164) 

I'm following the connection steps from a published Java book. In forums and tutorials, I just see the same code, cannot figure out why that exception is thrown.

On a normal application which does not run on the server the exception isn't thrown and the connection (in the exact same way) its successful.

Do you have any advice?

1
  • ah! Good ol' ClassNotFound. You probably need to copy MySQL jar to your app-server's lib directory. Commented Jan 29, 2011 at 7:36

2 Answers 2

3

Place the mysql-connector-x.jar in WEB-INF/lib

Sign up to request clarification or add additional context in comments.

Comments

1

Two possible solutions:

1) When you create the WAR, is that driver inside? You can unzip it (rename the .war file to .zip and just take a look -- it should be under /WEB-INF/lib.) Eclipse might not be exporting it to the WAR.

2) Did you put it into the Tomcat lib directory, if you're using Tomcat? If not, which servlet container are you deploying into?

One thing I've noticed is that sometimes, Java doesn't like there being spaces to a class. You should be able to avoid it by including it in either of the two solutions so it becomes a relative path, but you can try to eliminate the space and see if it helps.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.