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.
// 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);
}
}
}
Click the buttons below in order to simulate how Java connects to PostgreSQL.
When the JDBC driver, database URL, username, and password are correct, the program displays the following message:
PostgreSQL database connected successfully