Java, PostgreSQL, Software Development

How to connect Java to PostgreSQL using JDBC

This is a simple post that shows how to connect Java to PostgreSQL using JDBC. Although most Java developers do not use this technique anymore, frameworks still do, and the codes are abstracted away from us. Meanwhile, some may still use it for high-performance applications.

Java, PostgreSQL, and Other Requirements

The codes on this post are dated but will still work using the following specific items.

  • Windows 7 Professional SP1
  • PostgreSQL 9.4 for Windows
  • JDBC Driver 9.3-1102-jdbc41 For PostgreSQL

Create a Java Maven Project

To create a Maven project, follow the steps on this post How to create a Maven project in Eclipse. Just specify “jar” for packaging as we do not need to deploy this on a web container. Then, configure the pom.xml file to add the dependency for the PostgreSQL JDBC driver (see Software Environment above).

Connect Java To PostgreSQL using JDBC

Our application is a Maven project with only one Java class. So, the Java codes load the PostgreSQL JDBC driver and try to get a database connection. These two operations are within a try-catch clause because they may throw Exception on runtime.

Note that the codes do not query for data from my PostgreSQL database. Also, they do not update data in the PostgreSQL database. We need to use ResultSet and Statement interfaces to do those, and using them is pretty standard and straightforward.

Download Java PostgreSQL JDBC  Project

The Java codes for this post are available in the following links.

https://www.dropbox.com/s/p7pdlxp2xtvapg7/TurretaPostgresqlJDBC.zip?dl=0

Got comments, or suggestions? Please visit our Facebook page!

You Might Also Like