Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java ClassNotFoundException for org.h2.Driver

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);   }  } 
like image 914
Ashton Wilkins Avatar asked Oct 24 '10 11:10

Ashton Wilkins


People also ask

What is the driver for H2 database?

To use H2 database in your Java project, a compatible JDBC driver is required at runtime. The h2-version. jar file contains H2 JDBC driver, so you just need to make this jar file available in the project's classpath.


1 Answers

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> 
like image 110
rogerdpack Avatar answered Oct 17 '22 15:10

rogerdpack