DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • A Maven Story
  • Java Module Benefits With Example
  • Providing Enum Consistency Between Application and Data
  • The Generic Way To Convert Between Java and PostgreSQL Enums

Trending

  • Every Cache Miss Is a Tiny Tax on Your Performance
  • Stateless JWT Auth Microservice Architecture With Spring Boot 3 and Redis Sentinel
  • Pragmatica Aether: Let Java Be Java
  • The Missing `bandit` for AI Agents: How I Built a Static Analyzer for Prompt Injection
  1. DZone
  2. Data Engineering
  3. Databases
  4. How to Connect PostgreSQL With Java Application

How to Connect PostgreSQL With Java Application

Need help connecting the PosgreSQL database with your Java application?

By 
Gleb Antonov user avatar
Gleb Antonov
·
May. 27, 19 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
33.7K Views

Join the DZone community and get the full member experience.

Join For Free

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 database with Java application hosted with Jelastic PaaS.

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

create postgresql database
2. After creation, you’ll receive an email with your database access credentials (host, login, and password).
postgresql-access-credentials
3. Click the Config button next to your application server (Tomcat in our case) to access the configuration file manager and create a new mydb.cfg file in the /opt/tomcat/temp folder.
postgresql 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


postgresql connection details

Here:

  • {host} – link to your DB node without protocol part
  •  {db_name} – name of the database (Postgres, in our case)
  •  {user}  and {password}  – 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 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 our example application to your Tomcat server using the following link:

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

Note: Our example application already contains the jdbc-connector for the 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 server afterward to apply the changes).

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

open java application

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

Your request will be processed shortly displaying the result message.

connect postgresql database in java

9. Let’s access our database via phpPgAdmin to ensure that a new table was created (access credentials are provided via the email described in the second step of this guide).

create postgresql table

As you can see, a new table (named due to the date and time of the creation) has been successfully added by our Java application. The connection is successfully established! Try it out at one of the globally-available Jelastic service providers.

application PostgreSQL Java (programming language) Database Application server

Published at DZone with permission of Gleb Antonov. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • A Maven Story
  • Java Module Benefits With Example
  • Providing Enum Consistency Between Application and Data
  • The Generic Way To Convert Between Java and PostgreSQL Enums

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook