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).
1 2 3 4 5 | <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <version>9.3-1102-jdbc41</version> </dependency> |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | package com.turreta.postgresql.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class JdbcClientSample { public static void main(String[] args) { Connection connection = null; try { Class.forName("org.postgresql.Driver"); connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/turretadb", "postgres", "yourpassword"); if(connection != null) { System.out.println("Connection established"); } else { System.out.println("Unable to establish connection"); } } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { if(connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } } } |
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