我正在尝试使用 H2连接到 Java 中的数据库(使用 Eclipse 作为 IDE)。该示例确实(如下)引发了 ClassNotFoundException
。问题是,我确实将 h2 jar 文件添加到系统 CLASSPATH。我什至通过控制台中的 printenv
多次检查了它。我是否省略了一个步骤?
代码:
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);
}
}
最佳答案
在我的情况下(有点无关,但值得一提),我将它添加到我的 maven pom 中,错误消息消失了:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>xxx</version> <!-- ex: 1.2.140 -->
</dependency>
或者如果您只在单元测试期间使用 h2:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>xxx</version> <!-- ex: 1.2.140 -->
<scope>test</scope>
</dependency>
关于org.h2.Driver 的 java ClassNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4008011/