我正在尝试使用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);
}
}
使用<scope>test</scope>
不应该逻辑上工作。尝试使用<scope>runtime</scope>
或<scope>provided</scope>
,除非您只需要测试阶段。
在maven文档中,它表示正常使用应用程序不需要<scope>test</scope>
依赖项,并且仅适用于测试编译和执行阶段
https://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html
示例(下面)抛出ClassNotFoundException
然后驱动程序不在类路径上。
问题是,我确实将h2 jar文件添加到系统CLASSPATH中。我甚至在控制台中通过'printenv'检查了几次。
你是怎么做到的?请显示获得的输出。
我省略了一步吗?
我不能用提供的信息说。但是依赖于CLASSPATH
环境变量无论如何都是一种不好的做法,如果你在命令行上运行Java,你应该使用-cp
选项。像这样:
java -cp h2.jar com.acme.Program
有没有办法在我使用RUN菜单时设置Eclipse使用jar文件,这样我就不必一直从控制台运行?
是。在Eclipse下,将JAR添加到项目构建路径:右键单击项目,然后单击Properties> Java Build Path> Libaries> Add JARS ...(假设H2 JAR在相对于项目的目录中可用)。其他IDE有相同的方法来做到这一点。
在我的情况下(我使用sbt)改变
libraryDependencies += "com.h2database" % "h2" % "1.4.196" % Test
至
libraryDependencies += "com.h2database" % "h2" % "1.4.196"
我有以下错误(使用Intellij)
org.h2.Driver的java ClassNotFoundException
通过从我的pom中删除范围解决了这个问题。
是:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.197</version>
<scope>test</scope>
</dependency>
变成:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.197</version>
</dependency>
当我们将Maven Quickstart项目实现为对另一个项目的依赖时,将出现这种类型的错误。大多数情况下仅作为junit测试。因此在应用程序中它将无法工作。
<scope>[database_name]</scope>
应该包括您正在使用的数据库。如果将db从一个更改为另一个,请确保也更改范围。一旦我改变它,错误就消失了。
使用发布版本。
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
如果在build.gradle中使用Gradle更改依赖项:
testCompile group: 'com.h2database', name: 'h2', version: '1.4.199'
至
compile group: 'com.h2database', name: 'h2', version: '1.4.199'