H2 未找到适合 jdbc:h2:mem 的驱动程序:

H2 No suitable driver found for jdbc:h2:mem:

我正在尝试使用 H2 的示例。但是我无法创建内存数据库。当我 运行 以下程序时,我只收到一条错误消息:

java.sql.SQLException: No suitable driver found for jdbc:h2:mem at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:702) at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:251) at db.DBExample.main(DBExample.java:14)

在pom.xml中我包含了

<dependency>
   <groupId>com.h2database</groupId>
   <artifactId>h2</artifactId>
   <version>1.4.200</version>
   <scope>test</scope>
</dependency>

有人知道哪里出了问题吗?

import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class DBExample {
    public static void main(String[] a) throws Exception {

        var url = "jdbc:h2:mem:";
        try (var con = DriverManager.getConnection(url);
             var stm = con.createStatement();
             var rs = stm.executeQuery("SELECT 1+1")) {
             if (rs.next()) {
                 System.out.println(rs.getInt(1));
             }
        } catch (SQLException ex) {
            var lgr = Logger.getLogger(DBExample.class.getName());
            lgr.log(Level.SEVERE, ex.getMessage(), ex);
        }
    }
}

问题是因为您指定了<scope>test</scope>。 删除范围线。

This scope indicates that the dependency is not required for normal use of the application, and is only available for the test compilation and execution phases.

<dependency>
   <groupId>com.h2database</groupId>
   <artifactId>h2</artifactId>
   <version>1.4.200</version>
</dependency>

看看这里:driver not found