Erran Morad
Erran Morad

Reputation: 4753

How do I create a H2 database inside a java project in Eclipse?

I want to create an embedded H2 database in my simple java project in Eclipse. How do I do this programatically and package the db inside my code ? I tried a SO post for this and got an error in my code.

Code -

public static void main(String[]args){

    JdbcDataSource ds = new JdbcDataSource();
    ds.setURL("jdbc:h2:˜/test");
    ds.setUser("sa");
    ds.setPassword("sa");
    try {
        Connection conn = ds.getConnection();
    } catch (SQLException e) {
        e.printStackTrace();
    }

}

Error -

org.h2.jdbc.JdbcSQLException: A file path that is implicitly relative to the 
current working directory is not allowed in the database URL "jdbc:h2:˜/test". 
Use an absolute path, ~/name, ./name, or the baseDir setting instead. [90011-181]
    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.engine.ConnectionInfo.getName(ConnectionInfo.java:398)
    at org.h2.engine.Engine.openSession(Engine.java:45)
    at org.h2.engine.Engine.openSession(Engine.java:167)
    at org.h2.engine.Engine.createSessionAndValidate(Engine.java:145)
    at org.h2.engine.Engine.createSession(Engine.java:128)
    at org.h2.engine.Engine.createSession(Engine.java:26)
    at org.h2.engine.SessionRemote.connectEmbeddedOrServer(SessionRemote.java:347)
    at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:108)
    at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:92)
    at org.h2.Driver.connect(Driver.java:72)
    at org.h2.jdbcx.JdbcDataSource.getJdbcConnection(JdbcDataSource.java:190)
    at org.h2.jdbcx.JdbcDataSource.getConnection(JdbcDataSource.java:161)
    at MyCode.main(MyCode.java:8)

I saw this link - https://groups.google.com/forum/#!msg/h2-database/SlSwte0DLSU/eWj0UaejdkEJ and Where are my H2 database files?. Its not clear how I can get the exact path to test database on my windows pc.

How do I first access the test database and then create another database inside my java project ?

Thank you.

Upvotes: 3

Views: 14378

Answers (2)

Thomas Mueller
Thomas Mueller

Reputation: 50127

You have used the wrong character. You need to use ~ (tilde) and you have use ˜ (I don't know what it is, but it's not a tilde).

Upvotes: 8

kaqqao
kaqqao

Reputation: 15459

The location of the H2 files is very nicely documented. To view the contents, execute the h2.jar. It is not only the driver, but also an executable that will start a web-based applications for DB management.

Upvotes: 1

Related Questions