Java Database Connectivity(JDBC) is a Java API that establishes a connection between Java applications and databases (like PostgreSQL). We can integrate JDBC into a Java application and then establish a connection with the PostgreSQL database. Not sure how to proceed with this? No worries! In this tutorial, we’ll show you how to connect PostgreSQL to Java using step-by-step instructions.
How to Connect PostgreSQL to Java
Postgres JDBC is an open-source driver that helps users establish a connection between a Java program and a Postgres database. We can download this driver and integrate it with Java.
To connect the Postgres database to a Java Program, go through the following steps:
Step1: Integrate Postgres JDBC Driver into Your Java Project
We can integrate the Postgres JDBC driver into a Java project using JAR File or Maven dependency:
- Using JAR File
We can download the Postgres JDBC driver from Postgres’ official website. Once downloaded, add its JAR file to your Java project. Follow the below instructions to add the Postgres JDBC JAR file to Eclipse IDE:
First, right-click on the project, hover over the “Build Path”, and select the “Configure Build Path…” option:
From the pop-up window, navigate to the “Libraries” tab, left-click on the “Classpath”, and select the “Add External JARs…” button:
Now select the downloaded Postgres JDBC JAR file and hit the “Open” button:
Finally, click the “Apply and Close” button to add the selected JAR file to your project:
- Using Maven Dependency
Alternatively, you can create a maven project and modify its “pom.xml” file. To do that, simply add the latest dependency of the Postgres JDBC driver into the pom file, as follows:
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.7.3</version>
</dependency>
Using this method, there is no need to download the JDBC driver manually. Instead, Maven will automatically download all the essential JAR files from the remote repositories.
Step 2: Establish a Connection Between Postgres and Java
Now type the following code in your Java file to establish a connection with the Postgres database:
import java.sql.*;
public class PostgresJavaConnection {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
String conn = "jdbc:postgresql://localhost:5432/postgres";
String username = "postgres";
String pass = "1212";
Class.forName("org.postgresql.Driver");
try (Connection connect = DriverManager.getConnection(conn, username, pass)) {
System.out.println("Connection Established Successfully!");
} catch (SQLException excep) {
excep.printStackTrace();
}
}
}
Code Explanation
- First, we import the required classes like “Connection”, “DriverManager”, and “SQLException” from the “java.sql” package.
- In the main() method, we specify the URL to establish the Postgres-Java connection using JDBC.
- Next, we specify the database username and respective password.
- The next line of code registers the Postgres driver.
- We invoke the getConnection() method to make a connection between PostgreSQL and Java.
- Finally, we use the catch() block to catch the potential exceptions.
Output
The above snippet confirms the Postgres-Java connection establishment. Now, we can run any SQL query to perform database operations, such as table creation, deletion, etc.
Step 3: Fetch Table Data
We have already created a table named “article_details” in the “postgres” database. Let’s run the following Java code to fetch the data of the “article_details” table:
Statement sqlStatement = connect.createStatement();
ResultSet tbl = sqlStatement.executeQuery("SELECT * FROM article_details");
while (tbl.next()) {
String tableColumns = tbl.getString("article_title");
System.out.println("The Article Title = " + tableColumns);
}
Code Explanation
- After establishing the connection, we use the “createStatement()” method to send SQL statements to the database.
- Next, we use the executeQuery() method to execute the SELECT query. This retrieves the data from the “article_details” table.
- In the next line, we use the while loop with the next() method to traverse each record of the selected table.
- Finally, we print the retrieved table records on the console using Java’s println() method.
Output
The output shows that table rows have been successfully retrieved.
Step 4: Create a New Table
In the following snippet, we create a new Postgres table named “studentInfo”:
Statement sqlStatement = connect.createStatement();
String createNewTable = "CREATE TABLE studentInfo ("
+ "std_id serial PRIMARY KEY,"
+ "std_name TEXT,"
+ "std_email VARCHAR(255))";
sqlStatement.execute(createNewTable);
System.out.println("Table Created Successfully!");
Code Explanation
- First, we use the CREATE TABLE statement to create a new ” studentInfo ” table.
- Next, we invoke the execute() method to execute the CREATE TABLE statement.
Output
The following output shows that a new table has been successfully created in the postgres database:
This way we can execute any SQL query from Java to perform database operations like data insertion, table deletion, etc.
Conclusion
We can connect PostgreSQL to Java using an open-source JDBC driver. We can use the JAR File or Maven dependency to integrate the Postgres JDBC driver into a Java project. Once Postgres is integrated with Java, we can use the getConnection() method to establish the Postgres-Java connection. After establishing a connection, we can execute any SQL query to perform a database operation, as illustrated in this post.