Connecting PostgreSQL DB with JDBC Driver using Java code

In this example, let us see how to connect Postgresql  database in java  with JDBC driver. The following code loads the Postgres JDBC Driver and connects to the postgres database and prints the records of the employee table.

For running the program you have to do the following.

1. Create database name “test” in postgres, create a table called “employee” and insert some records.

CREATE DATABASE test WITH OWNER = postgres ENCODING = 'UTF8' TABLESPACE = pg_default LC_COLLATE = 'English_United States.1252' LC_CTYPE = 'English_United States.1252'
CONNECTION LIMIT = -1;

CREATE TABLE employee (name character varying,empcode character varying)

insert into employee (empcode, name) values ('1', 'Kumar');

insert into employee (empcode, name) values ('2', 'Kamal'); 

2. Download latest Postgres JDBC driver from the postgres site. In this example, i have used the driver “postgresql-9.4-1201.jdbc4.jar”

3. Add the jar to the class path in Eclipse.  If you want to run on command prompt, then set the CLASSPATH as follows

set CLASSPATH=.;F:\Jars\postgres\postgresql-9.4-1201.jdbc4.jar. where “F:\Jars\postgres” is the folder where the driver is located.  OR You can  mention the classpath when running the program as mentioned below

java -cp d:\Sun\SDK\jdk\lib\postgresql-9.4-1201.jdbc4.jar; PGSQLJDBCConnect

//code starts

package net.javaonline;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;

public class PGSQLJDBCConnect {
  public static void main(String[] argv) {

   try {
     Class.forName("org.postgresql.Driver");

    } catch (ClassNotFoundException e) {
      System.out.println("Please set your classpath to Where your PostgreSQL is located");
      e.printStackTrace();
      return;
      }

 System.out.println("PostgreSql driver is loaded successfully");

   Connection conn = null;
   PreparedStatement pstmt = null;
   ResultSet rs=null;
   boolean found=false;

   try {

           conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/test","postgres", "*****");

        if (conn != null)
		  {
		    System.out.println("Database Connected");
		  }
        else
		  {
           System.out.println("Failed to make connection");
	        }

		  pstmt=conn.prepareStatement("Select * from employee");
		  rs=pstmt.executeQuery();

		       if(rs!=null)
		  {

		  while(rs.next())
		   {
			   found=true;
			   System.out.println("Code: "+rs.getString("empcode"));
			   System.out.println("Name: "+rs.getString("name"));
		   }
		   }

		  if (found ==false)
		  {
			  System.out.println("No Records Found");
		  }

		   } catch (SQLException e) {
			     System.out.println("Database connection Failed");
			     e.printStackTrace();
			     return;
		     }

}
}

 

Running the program on Eclipse

java postgres connect