java ClassNotFoundException for org.h2.Driver

Ashton Wilkins picture Ashton Wilkins · Oct 24, 2010 · Viewed 76.7k times · Source

I am trying to use H2 to connect to a database in Java (using Eclipse as the IDE). The sample does (below) throws a ClassNotFoundException. The thing is, I did add the h2 jar file to the system CLASSPATH. I have even checked it's there several times via printenv in the console. Am I omitting a step?

CODE:

import java.sql.*;

public class Program {

 /**
  * @param args
  */
 public static void main(String[] args) 
  throws Exception{

  try{
   System.out.println("hello, world!");
   Class.forName("org.h2.Driver");
   Connection conn = DriverManager.getConnection("jdbc:h2:~/testdb", "sa", "");
   // add application code here
   conn.close();
  }catch(ClassNotFoundException ex){
   System.out.println( "ERROR: Class not found: " + ex.getMessage() );

  }
  System.exit(0);

 }

}

Answer

rogerdpack picture rogerdpack · Jul 31, 2013

In my case (unrelated a bit, but worth mentioning), I added this to my maven pom, and the error message went away:

  <dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>xxx</version> <!-- ex: 1.2.140 -->
  </dependency>

or if you are only using h2 during unit testing:

  <dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>xxx</version> <!-- ex: 1.2.140 -->
    <scope>test</scope>
  </dependency>