H2 连接失败

H2 connection fails

我正在尝试连接到本地 H2 数据库,使用简单的代码:

    Class.forName("org.h2.Driver");
    Connection conn = DriverManager.getConnection("jdbc:h2:~/test", "sa", "");

另一方面,我还使用自己的 jdbc 驱动程序连接到远程 Oracle 服务器。根据我的理解,两者可以共存,因为 jdbc 驱动程序不同,并且根据连接 url 使用正确的驱动程序。所以这不应该是我问题的根源。

失败并出现以下错误:

org.h2.jdbc.JdbcSQLException: File corrupted while reading record: "[16] stream data key:7 pos:11 remaining:0". Possible solution: use the recovery tool [90030-190]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
    at org.h2.message.DbException.get(DbException.java:179)
    at org.h2.message.DbException.get(DbException.java:155)
    at org.h2.index.PageBtreeIndex.getPage(PageBtreeIndex.java:156)
    at org.h2.index.PageBtreeIndex.<init>(PageBtreeIndex.java:69)
    at org.h2.table.RegularTable.addIndex(RegularTable.java:234)
    at org.h2.store.PageStore.addMeta(PageStore.java:1738)
    at org.h2.store.PageStore.readMetaData(PageStore.java:1637)
    at org.h2.store.PageStore.recover(PageStore.java:1405)
    at org.h2.store.PageStore.openExisting(PageStore.java:367)
    at org.h2.store.PageStore.open(PageStore.java:288)
    at org.h2.engine.Database.getPageStore(Database.java:2464)
    at org.h2.engine.Database.open(Database.java:672)
    at org.h2.engine.Database.openDatabase(Database.java:269)
    at org.h2.engine.Database.<init>(Database.java:263)
    at org.h2.engine.Engine.openSession(Engine.java:65)
    at org.h2.engine.Engine.openSession(Engine.java:175)
    at org.h2.engine.Engine.createSessionAndValidate(Engine.java:153)
    at org.h2.engine.Engine.createSession(Engine.java:136)
    at org.h2.engine.Engine.createSession(Engine.java:28)
    at org.h2.engine.SessionRemote.connectEmbeddedOrServer(SessionRemote.java:349)
    at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:107)
    at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:91)
    at org.h2.Driver.connect(Driver.java:72)
    at java.sql.DriverManager.getConnection(DriverManager.java:664)
    at java.sql.DriverManager.getConnection(DriverManager.java:247)

我仍然可以使用在端口 8082 上运行的 Web 控制台进行连接。

好吧,我找到了解决问题的方法:将连接 url 更改为

"jdbc:h2:tcp://localhost/~/test"

根据 H2 Features • Database URL Overview,有许多可用的 URL 表达式,这里有一些例子:

  • 嵌入式(本地)连接:
    • jdbc:h2:~/test
    • jdbc:h2:file:/data/sample
    • jdbc:h2:file:C:/data/sample(仅限 Windows)
  • 内存中(已命名):
    • jdbc:h2:mem:test_mem
  • 服务器模式(远程连接)使用TCP/IP:
    • jdbc:h2:tcp://localhost/~/test
    • jdbc:h2:tcp://dbserv:8084/~/sample
    • jdbc:h2:tcp://localhost/mem:test
  • ...

还有很多,请查看上面link以查看完整列表。