anzie001
anzie001

Reputation: 241

How to connect to heroku postgress database from JDBC?

I use this code But can anyone suggest me or guide me to a right document which can give me an example of how to connect to heroku postgress database with JDBC ?

    URI dbUri = new URI(System.getenv("DATABASE_URL"));
    String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + 
    dbUri.getPath();
    connectionPool = new BasicDataSource();

    if (dbUri.getUserInfo() != null) {
        connectionPool.setUsername(dbUri.getUserInfo().split(":")[0]);
        connectionPool.setPassword(dbUri.getUserInfo().split(":")[1]);
    }
    connectionPool.setDriverClassName("org.postgresql.Driver");
    connectionPool.setUrl(dbUrl);
    connectionPool.setInitialSize(1);

    Connection connection = connectionPool.getConnection();

Upvotes: 1

Views: 827

Answers (1)

LiorH
LiorH

Reputation: 18824

See heroku's documentation

Note:

The DATABASE_URL for the Heroku Postgres add-on follows the below convention

postgres://<username>:<password>@<host>:<port>/<dbname>

However the Postgres JDBC driver uses the following convention:

jdbc:postgresql://<host>:<port>/<dbname>?user=<username>&password=<password>

Sample code to parse DATABASE_URL into Jdbc format:

private static Connection getConnection() throws URISyntaxException, SQLException {
   URI dbUri = new URI(System.getenv("DATABASE_URL"));
   String username = dbUri.getUserInfo().split(":")[0];
   String password = dbUri.getUserInfo().split(":")[1];
   String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + ':' + dbUri.getPort() + dbUri.getPath();

   return DriverManager.getConnection(dbUrl, username, password);
}

Upvotes: 1

Related Questions