Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
597 views
in Technique[技术] by (71.8m points)

java - Start H2 database programmatically

I'm coding a server-client application in Java and I need to implement a local database on the server side and I decided to go for H2 database engine.

One more thing to add is that I usa TCP connection to start and run the database. This is what I put together so far:

Class.forName("org.h2.Driver");  
Server server = Server.createTcpServer(DB_PATH).start();

Connection currentConn = DriverManager.getConnection(DB_PATH, DB_USER, DB_PASSWORD);   

Where the connection string is jdbc:h2:tcp://localhost/~/test.

That piece of code returns with an exception:

Feature not supported: "jdbc:h2:tcp://localhost/~/test" [50100-176]

I followed this article.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Something like this should work

Server server = null;
            try {
                server = Server.createTcpServer("-tcpAllowOthers").start();
                Class.forName("org.h2.Driver");
                Connection conn = DriverManager.
                    getConnection("jdbc:h2:tcp://localhost/~/stackoverflow", "sa", "");
                System.out.println("Connection Established: "
                        + conn.getMetaData().getDatabaseProductName() + "/" + conn.getCatalog());
             
            } catch (Exception e) {
                e.printStackTrace();
            }
        

and the output is Connection Established: H2/STACKOVERFLOW

This has been tested with h2-1.4.184


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...