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); } }
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With