6

I use the in-memory database that comes with Play Framework, when I have db=mem in the configuration file, for development.

How can I connect to this database using JDBC? and not the JPA that is the default way.

I have tried with this method in my controller:

public static void addToDB() {
    try {
        Connection conn = DriverManager.getConnection("jdbc:h2:mem:play");
        Statement stmt = conn.createStatement();
        stmt.execute(sql);
        stmt.close();
        conn.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

But I get an error message that I need to provide an username and password:

org.h2.jdbc.JdbcSQLException: Wrong user name or password [8004-149]

If I visit the web-console on /@db the username sa is used and no password.


Now I logged in via the /@db interface and created a table users.

Then I connected to the database in a controller method and used this jdbc-string: jdbc:h2:mem:play:sa and then tried to insert to the table users but I get this error message:

org.h2.jdbc.JdbcSQLException: Table "USERS" not found; SQL statement:

How should I connect to the in-memory H2 database in Play Framework using JDBC?

2 Answers 2

8

DB.getConnection(), should do the job.

Sign up to request clarification or add additional context in comments.

2 Comments

Is a new connection returned every time I call it? or is it the same that I shouldn't close?
It the connection given from the HibernateSession. So I would assume that it's better you don't close it.
7

Try:

Connection conn = DriverManager.getConnection("jdbc:h2:mem:play", "sa", "");

because as you wrote, "the username sa is used and no password."

1 Comment

+1 I was confusing the URL name with the user name; thanks for clarifying.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.