Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

H2 database in memory mode cannot be accessed by Console

I am creating an in memory database in H2 database by the following code on servlet context startup

    void initDb()  {
    try {

        webserver = Server.createWebServer().start();

        Class.forName("org.h2.Driver");
        Connection conn = DriverManager.getConnection("jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1","SA","");
        InputStream in = getClass().getResourceAsStream("script.sql");
        if (in == null) {
            System.out.println("Please add the file script.sql to the classpath, package " + getClass().getPackage().getName());
        } else {
            RunScript.execute(conn, new InputStreamReader(in));
            Statement stat = conn.createStatement();
            ResultSet rs = stat.executeQuery("SELECT TO_CHAR(bday,'DD/MM/yyyy hh24:mi') FROM TEST2");
            while (rs.next()) {
                System.out.println(rs.getString(1));
            }
            rs.close();
            stat.close();
            conn.commit();
            conn.close();
        }




    //accessed using url jdbc:h2:tcp://localhost/mem:db1    
    try{ 

                CachedRowSet crs = new DBConnector().executeQuery("select * from  test2"); 
                while(crs.next()){ 
                System.out.println("ARGUMENT_NAME:"+crs.getString(1)); 
               // System.out.println(",DATA_TYPE:"+crs.getString("DATA_TYPE"));       
                } 
                crs.close(); 
        }catch(SQLException e){ 
            e.printStackTrace(); 
        } 

    } catch (Exception e) { //this exception gets throws connection failed!
        System.out.println("Exception initializing memory H2 database"+e);
    }
}

I am later on accessing by url jdbc:h2:mem:db1 in the same JVM, which is working too. But when i want to access it by jdbc:h2:tcp://localhost/mem:db1 it is not working either in the same JVM or in different JVM.

I actually want to run the system in embedded mode and see the contents using the console. If I start the webserver in the same servlet context startup method I am able to see the Console but it is still not connecting to the in memory DB with url jdbc:h2:tcp://localhost/mem:db1.

If I start the server using Command line using

java -cp "WebContent/WEB-INF/lib/h2-1.3.148.jar;hsqldb.jar;%H2DRIVERS%;%CLASSPATH%"  org.h2.tools.Console %*
and url as 'jdbc:h2:tcp://localhost/mem:db1'

And then try to connect, surprisingly it connects but with no data. Seems like it is creating a seperate server on its own and its a different db. So there is no data.

like image 617
samarjit samanta Avatar asked Feb 22 '11 11:02

samarjit samanta


People also ask

How do I access H2 in-memory database?

Accessing the H2 Console H2 database has an embedded GUI console for browsing the contents of a database and running SQL queries. By default, the H2 console is not enabled in Spring. Then, after starting the application, we can navigate to http://localhost:8080/h2-console, which will present us with a login page.

How do I access the H2 database console?

You can access the console at the following URL: http://localhost:8080/h2-console/. You need to enter the JDBC URL, and credentials.

Is H2 in-memory database?

H2 is an embedded, open-source, and in-memory database. It is a relational database management system written in Java. It is a client/server application. It stores data in memory, not persist the data on disk.

How to access the H2 database in memory mode?

Now you can connect to your database via jdbc:h2:mem:foo_db URL within the same process or browse the foo_db database using localhost:8082. Remember to close both servers. See also: H2 database in memory mode cannot be accessed by Console. BTW you should only depend on assertions and not on manual peeking the database contents.

What is the H2 console application?

The H2 Console application lets you access a database using a browser. This can be a H2 database, or another database that supports the JDBC API. This is a client/server application, so both a server and a client (a browser) are required to run it.

Is JDBC H2 client/server mode supported for in memory databases?

Explicit client/server connections (using jdbc:h2:tcp:// or ssl://) are not supported. This mode is not supported for in-memory databases. Here is an example how to use this mode.

What is the logger name of h2database?

The logger name is h2database . If it does not work, check the file <database>.trace.db for error messages. If the database files are read-only, then the database is read-only as well. It is not possible to create new tables, add or modify data in this database.


1 Answers

To make the in-memory database available for another process, you need to start a TCP server in the same process as the database was opened. Example:

package db;

import java.sql.Connection;
import java.sql.DriverManager;
import org.h2.tools.Server;

public class TestMem {
    public static void main(String... args) throws Exception {

        // open the in-memory database within a VM
        Class.forName("org.h2.Driver");
        Connection conn = DriverManager.getConnection("jdbc:h2:mem:test");
        conn.createStatement().execute("create table test(id int)");

        // start a TCP server
        // (either before or after opening the database)
        Server server = Server.createTcpServer().start();

        // .. use in embedded mode ..

        // or use it from another process:
        System.out.println("Server started and connection is open.");
        System.out.println("URL: jdbc:h2:" + server.getURL() + "/mem:test");

        // now start the H2 Console here or in another process using
        // java org.h2.tools.Console -web -browser

        System.out.println("Press [Enter] to stop.");
        System.in.read();

        System.out.println("Stopping server and closing the connection");
        server.stop();
        conn.close();
    }
}
like image 200
Thomas Mueller Avatar answered Oct 19 '22 23:10

Thomas Mueller