Hackerss.com

hackerss
hackerss

Posted on

Java How to connect to a postgresql


import java.sql.*;
import java.util.Scanner;

public class Postgresql {

   public static void main(String[] args) throws Exception {
      // TODO Auto-generated method stub
      Connection conn = null;
      try {
         // Register the JDBC driver for Postgres
         Class.forName("org.postgresql.Driver");
         // Connect to the database
         conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgres", "postgres", "postgres");
         // Execute a query
         Statement stmt = conn.createStatement();
         String sql = "SELECT * FROM public.\"Employee\"";
         ResultSet rs = stmt.executeQuery(sql);
         // Iterate through the result set
         while (rs.next()) {
            System.out.println(rs.getString("first_name") + " " + rs.getString("last_name"));
         }
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         if (conn != null) {
            conn.close();
         }
      }

   }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)