Search code examples
databaseodbch2

how can i access h2db using pg server?


i want access h2db using pg server because i want access db using odbc in c language. So I'm now testing access to db with pg server with java.

import java.sql.*;

public class Main {
    public static void main(String[] a) {
        try {
            Class.forName("org.h2.Driver");
            Connection conn = DriverManager.getConnection("jdbc:h2:tcp://localhost:5435/~/db_test;CIPHER=AES;", "sa", "0df ");
            System.out.println("success");
            conn.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

and it print error: org.h2.jdbc.JdbcSQLNonTransientConnectionException: Connection is broken: "unexpected status 1375731712" [90067-214]

Is there a solution to this?

I tried connecting this to a tcp server, and then it was successful. but not pg


Solution

  • First of all, you need to create your database if it doesn't exist yet. You can use JDBC or any other way. For encrypted databases password of database file and password of database user must be specified together separated by the space character:

    DriverManager.getConnection("jdbc:h2:~/db_test;CIPHER=AES", "sa",
            "file_password user_password")
        .close();
    

    You cannot pass H2-specific paths and settings through PG protocol, so you need create an alias for your database with the -key option when you start the PG server of H2:

    Server.createPgServer("-pgPort", "5435",
            "-key", "db_test", "~/db_test;CIPHER=AES")
        .start();
    

    Your client application must have PostgreSQL JDBC Driver in its classpath, use this driver to establish a connection instead of H2's own driver:

    Connection conn = DriverManager.getConnection(
            "jdbc:postgresql://localhost:5435/db_test",
            "sa", "file_password user_password");