Search code examples
javamysqljdbcclassnotfoundexception

classNotFound Exception when using JDBC for MYSQL on Tomcat in eclipse


This seems to be a common problem, but I could not find a working solution. I've looked through dozens of thread and have been working with my teacher. I am trying to connect to MYSQL using JDBC. I'm also using a tomcat server and running xubuntu 12.04. I am getting ClassNotFound exception.

I've tried the JDBC mysql-connector-java.jar driver placed in both /tomact/lib and /usr/share/java and have manually built paths in each instance. I've also tried adding paths through deploy assembly. I've tried using EXPORT CLASSPATH. Nothing has worked. I cannot get this exception to stop being thrown. Does anyone have other solutions I can try?

my code:

public static Connection getConnection() {
    if(connection!=null){
        return connection;
    }else{
        try{
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            String dbURL = "jdbc:mysql://144.91.20.136:3306/jewelryInventoryGallison";
            String username = "javaee";
            String password = "mills2012";

            connection = DriverManager.getConnection(dbURL, username, password);
            return connection;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }
}

test class:

public static void main(String[] args) throws Exception{ 
      Connection conn = DatabaseUtils.getConnection();
      Statement st = conn.createStatement();
      ResultSet rs = st.executeQuery("SELECT * FROM Inventory");
      while(rs.next()) {
       System.out.println(rs.getString("name"));
      }

 }

and trace:

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:186)
at utils.DatabaseUtils.getConnection(DatabaseUtils.java:19)
at utils.DatabaseUtils.main(DatabaseUtils.java:34)

Exception in thread "main" java.lang.NullPointerException at utils.DatabaseUtils.main(DatabaseUtils.java:35)

your help will be greatly appreciated!


Solution

  • Eventhough connector is configured in classpath tomcat doesn't load that correctly. so paste the mysql-connector-jar file in lib folder under WEB_INF also and try running again.

    enter image description here