Book Image

Learning Heroku Postgres

By : Patrick Rafael de Oliveira Espake
Book Image

Learning Heroku Postgres

By: Patrick Rafael de Oliveira Espake

Overview of this book

Table of Contents (17 chapters)
Learning Heroku Postgres
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Keyword List
Index

Connecting with Java


There are many ways to connect to the database using Java, the most common way is through the parameters contained in the database connection URL. It provides you with the information postgres://[username]:[password]@[host]/[database name].

JDBC

You can connect via JDBC using the DATABASE_URL variable or using another database URL provided by Heroku. The JDBC connection is performed through the database URL parsing and extracting the necessary parameters. The following is just a code sample to help you understand the concept:

URI connectionParams = new URI(System.getenv("DATABASE_URL"));
String jdbcUrl = "jdbc:postgresql://" + connectionParams.getHost() + connectionParams.getPath(); 
Properties properties = new Properties();
properties.setProperty("username", connectionParams.getUserInfo().split(":")[0]);
properties.setProperty("password", connectionParams.getUserInfo().split(":")[1]);
Connection connection = DriverManager.getConnection(jdbcUrl, properties);

Spring/XML...