Steps to Run Your JDBC Program:

  1. Download the PostgreSQL JDBC driver from http://www.retep.org.uk/postgres/.
  2. Set your CLASSPATH to the path where the JDBC driver is located. For example, use
    setenv CLASSPATH .:~/jar/jdbc6.5-1.1.jar.
  3. Create the sample JDBC code (psqljdbc.java) as shown in below.
  4. Compile it by javac psqljdbc.java.
  5. Run it by java psqljdbc.

This is the JDBC code to access PostgreSQL.

/* 
 * Java sample program - psqljdbc.java
 */ 
          
import java.io.*; 
import java.sql.*; 
          
public class psqljdbc 
{ 
   Connection  conn;                     // holds database connection 
   Statement   stmt;                     // holds SQL statement 
   String      state_code;               // holds state code entered by user 
          
   public psqljdbc() throws ClassNotFoundException,
                          FileNotFoundException, IOException, SQLException 
   { 
     Class.forName("postgresql.Driver");   // load database interface 
                                               // connect to the database 
     conn = DriverManager.getConnection("jdbc:postgresql://roger/cs898n", 
                                        "cs898n", "abc123"); 
     stmt = conn.createStatement(); 
        
     ResultSet res = stmt.executeQuery(           // send the query 
       "select * from friend");

     if (res != null)  
       while(res.next())  
       { 
         String fname = res.getString(1); 
         System.out.println(fname); 
       } 
          
     res.close(); 
     stmt.close(); 
     conn.close(); 
   } 
          
   public static void main(String args[]) 
   { 
     try { 
       psqljdbc test = new psqljdbc(); 
     } catch(Exception exc)  
     { 
        System.err.println("Exception caught.\n" + exc); 
        exc.printStackTrace(); 
     } 
   } 
}