Connect PostgreSQL to Java Application with Jelastic PaaS

25

PostgreSQL is a powerful, open source SQL database with the object-relational structure and numerous robust features to ensure excellent performance and reliability. In this tutorial, we’ll show how to connect PostgreSQL to a Java application with Jelastic PaaS.

1. Log into your Jelastic PaaS dashboard, create New Environment with the Java application server and the PostgreSQL database.

3759-1-create-environment-with-postgresql-database

2. After creation, you’ll receive an email with your database access credentials (host, login, and password).

3759-1-postgresql-database-access-credentials

3. Click the Config button next to your application server (Tomcat in this case) to access the configuration file manager and create a new mydb.cfg file in the /opt/tomcat/temp folder.

3759-1-postgresql-database-configuration-files

4. Provide the following connection details in the mydb.cfg file:

host=jdbc:postgresql://{host}/{db_name}
username={user}
password={password}
driver=org.postgresql.Driver

3759-1-postgresql-database-connection-details

Where:

  • {host} – host address of your database node without protocol part;
  • {db_name} – name of the database (postgres in this case);
  • {user} and {password} – database admin user credentials.
Note: Usually, for production, it is recommended defining a new restricted user via phpPgAdmin for your application with access to the dedicated database only. However, for this example, we’ll take the default user (i.e., webadmin with full administrative access to the server) and database (postgres).

5. Below, you can see the code of the Java application used in this tutorial.

package connection;
  
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
  
public class DbManager {
  
    public String date = new SimpleDateFormat("dd-MM-yyyy-HH-mm").format(new Date());
    private final String createTable = "CREATE TABLE \"" + date + "\" (id INT, data VARCHAR(100));";
    private static final int LoginTimeout = 10;
  
    public DbManager() {
    }
  
    public Connection createConnection() throws IOException, ClassNotFoundException, SQLException {
        Properties prop = new Properties();
        System.out.println("\n\n=======================\nJDBC Connector Test " + date);
        System.out.println("User home directory: " + System.getProperty("user.home"));
        String host;
        String username;
        String password;
        String driver;
        try {
            prop.load(new java.io.FileInputStream(System.getProperty("user.home") + "/mydb.cfg"));
  
            host = prop.getProperty("host").toString();
            username = prop.getProperty("username").toString();
            password = prop.getProperty("password").toString();
            driver = prop.getProperty("driver").toString();
        } catch (IOException e) {
            System.out.println("Unable to find mydb.cfg in " + System.getProperty("user.home") + "\n Please make sure that configuration file created in this folder.");
              
            host = "Unknown HOST";
            username = "Unknown USER";
            password = "Unknown PASSWORD";
            driver = "Unknown DRIVER";
        }
  
        System.out.println("host: " + host + "\nusername: " + username + "\npassword: " + password + "\ndriver: " + driver);
  
        Class.forName(driver);
        System.out.println("--------------------------");
        System.out.println("DRIVER: " + driver);
        System.out.println("Set Login Timeout: " + LoginTimeout);
        DriverManager.setLoginTimeout(LoginTimeout);
        Connection connection = DriverManager.getConnection(host, username, password);
        System.out.println("CONNECTION: " + connection);
  
        return connection;
    }
  
    public String runSqlStatement() {
        String result = "";
        try {
            Statement statement = createConnection().createStatement();
            System.out.println("SQL query: " + createTable);
            statement.execute(createTable);
        } catch (IOException | ClassNotFoundException ex) {
            Logger.getLogger(DbManager.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("Exception occurred: " + ex);
            result = ex.getMessage();
        } catch (SQLException ex) {
            ex.printStackTrace();
            result = ex.getMessage();
        }
        return result;
    }
}

6. Deploy the example Java application to your Tomcat server using the following link:

https://download.jelastic.com/public.php?service=files&t=18753849900d2461b3162bd4355f834d&download

3759-1-deploy-java-application

Note: This example Java application already contains the jdbc-connector for PostgreSQL database access. However, for other projects, you may need to manually upload it to the webapps/{app_context}/WEB-INF/lib folder on your application server (don’t forget to restart the application server afterwards to apply the changes).

7. After successful deployment, click Open in Browser next to your application server.

3759-1-open-java-application-in-browser

8. Within the opened browser tab, click the Create test table in your database button.

3759-1-java-jdbc-test-connection

Your request will be processed shortly and a result message is being displayed.

3759-1-java-jdbc-test-connection-result

9. Access the database via phpPgAdmin to see that a new table was created (the access credentials are provided via the email as described in the second step of this tutorial).

3759-1-phppgadmin-postgresql-table-created

As you can see, a new table (named due to the date and time of the creation) has been successfully added by the example Java application. The connection is successfully established! Try it yourself with a free trial at our Jelastic PaaS platform.

SOURCEJelastic, Inc.