← Back to Chapters

PostgreSQL Connection (JDBC)

? PostgreSQL Connection (JDBC)

? Quick Overview

PostgreSQL is a powerful open-source relational database system. In Advance Java, JDBC is used to connect Java applications with PostgreSQL databases to perform CRUD operations securely and efficiently.

? Key Concepts

  • PostgreSQL JDBC Driver
  • DriverManager
  • Connection Interface
  • Statement / PreparedStatement
  • ResultSet

? Syntax / Theory

  • Load PostgreSQL JDBC driver
  • Establish database connection
  • Create SQL statement
  • Execute query or update
  • Close database resources

? Code Example – PostgreSQL JDBC Connection

? View Code Example
// Import required PostgreSQL JDBC classes
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class PostgreSQLConnectionDemo {
public static void main(String[] args) {
try {
// Load PostgreSQL JDBC Driver
Class.forName("org.postgresql.Driver");

// Establish connection with PostgreSQL database
Connection con = DriverManager.getConnection(
"jdbc:postgresql://localhost:5432/testdb",
"postgres",
"password"
);

// Create SQL statement object
Statement stmt = con.createStatement();

// Display success message
System.out.println("PostgreSQL database connected successfully");

// Close database connection
con.close();
} catch (Exception e) {
// Handle connection or driver errors
System.out.println(e);
}
}
}

? Interactive JDBC Lifecycle

Click the buttons below in order to simulate how Java connects to PostgreSQL.

 
 
1Load Driver
2Connect
3Execute
4Close
 
> System ready...
> Waiting for user input...

? Live Output / Explanation

Expected Output

When the JDBC driver, database URL, username, and password are correct, the program displays the following message:

PostgreSQL database connected successfully

✅ Tips & Best Practices

  • Always use PreparedStatement to prevent SQL injection
  • Close Connection, Statement, and ResultSet objects properly
  • Use connection pooling in large applications
  • Keep database credentials outside source code

? Try It Yourself

  • Create a PostgreSQL table and retrieve records using JDBC
  • Insert and update records using PreparedStatement
  • Build a small Java program to display table data