Here’s a sample code snippet that demonstrates how to read data from a PostgreSQL database using Java and JDBC (Java Database Connectivity):
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class PostgreSQLDataReader { public static void main(String[] args) { // Database credentials String url = "jdbc:postgresql://localhost:5432/mydatabase"; String username = "postgres"; String password = "password"; // SQL query String query = "SELECT * FROM customers"; try { // Register JDBC driver Class.forName("org.postgresql.Driver"); // Open a connection Connection conn = DriverManager.getConnection(url, username, password); // Create a statement Statement stmt = conn.createStatement(); // Execute the query ResultSet rs = stmt.executeQuery(query); // Process the result set while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); String email = rs.getString("email"); System.out.println("ID: " + id); System.out.println("Name: " + name); System.out.println("Email: " + email); System.out.println("--------------------------"); } // Close the resources rs.close(); stmt.close(); conn.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } }
Make sure to replace the url
, username
, and password
variables with your actual PostgreSQL database connection details. Additionally, modify the query
variable to match your desired SQL query.
This code snippet assumes you have the PostgreSQL JDBC driver (e.g., postgresql.jar
) included in your classpath. If not, you can download it from the official PostgreSQL website or include it as a Maven/Gradle dependency.
The code connects to the PostgreSQL database, executes the SQL query, and iterates over the result set to retrieve the data. In this example, it assumes a table named “customers” with columns “id,” “name,” and “email.” Adjust the column names as per your table schema.
Remember to handle exceptions appropriately in your production code and consider using try-with-resources or a similar mechanism to automatically close the resources.