1

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();
anzie001
  • 231
  • 3
  • 12

1 Answers1

1

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);
}
LiorH
  • 18,524
  • 17
  • 70
  • 98
  • So , i saw that, and i believe problem lies with my DATABASE_URL environment, since when i am trying to get it's value, there is no username/password attached to it. May be it is because i haven't set the value of DATABSE_URL anywhere ? I am getting this error : Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections. – anzie001 May 09 '17 at 19:51
  • make sure there's a DATABASE_URL in your heroku config - `heroku config | grep DATABASE_URL` if there's none, then promote the DB `heroku pg:promote HEROKU_POSTGRESQL_XXX` where XXX is the color of the DB. – LiorH May 10 '17 at 05:54