JDBC PostgreSQL Connection

In this tutorial we will connect a Java application to a PostgreSQL database using JDBC.

1. Prerequisites

  1. Eclipse
  2. JDBC PostgreSQL driver (https://jdbc.postgresql.org/download.html)
  3. Running PostgreSQL database

2. Create standard Java project

  1. In Eclipse, create a new Java project
  2. Create a folder called “lib” in the root folder of the project
  3. Copy the JDBC driver into that “lib” folder
  4. Right click the JDBC jar file and select Build Path Add to Build Path

3. JDBC PostgreSQL connection example

At first we need a wrapper class to connect to a selected database. Do not forget to adapt your package location if you use another location. You can use the follwing code:

In the constructor you pass the database URL, username, password and a boolean whether you are using SSL (encryption). Afterwards you can use the getConnection() to work with the established connection. Do not forget to call the close() function to free resources.

4. PostgreSQL CRUD operations

Now we can connect to the database and create tables, insert, update, delete and select data:

5. Execute the code

Here is a Main function to test and manipulate the JDBC PostgreSQL Connection. Do not forget to replace the url, user and password with your own credentials.

You should get the following output:

If you have problems or questions feel free to comment and ask.



Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.