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

 

rock hard male enhancement pills best male enhancement reviews size penis enhancement results king male enhancement libido supplement penile enhancement before and after surgery penile enlargement costs sex pills hairy goat andro400 supplement where to buy pxl male enhancement red male enhancement sean hanity show tumblr gay penis enlargement fetish v8 super energy male enhancer chinese sex enhancement exercise hammer of thor medicine penis enlargement kama sutra wasp sleeping pills sex story sex pills to makeme cum faster king size erectile dysfunction pills review strike for men male sexual enhancement

is cbd oil and hemp oil the same dr sterns cbd cbd in new york cbd and seizures in adults will cbd oil show on drug test cbd oil trial empower cbd cbd oil lazarus naturals cbd pure review is cbd oil safe for pregnant women buy cbd cigarettes cbd drowsiness cbd for parkinson pharmaceutical grade cbd isolate benefits of cbd edibles cbd sciences full spectrum cbd oil reddit odessa cbd oil cannabis oil extractor cbd pill

tuna diet weight loss warrior diet weight loss 1 week weight loss pill phentermine side effects garcinia cambogia pills to lose weight keto diet recipes cookies capricorn weight loss diet best diets to lose weight fast and keep it off weight loss pill from doctor pills for womens weight loss n sex enhancer vegan diets to lose weight fast best all natural weight loss pills 2020 disputing prescription pills weight loss neli weight loss pills reviews medicine that helps you lose weight mediterranean diet plan for weight loss uk network organic diet tea for weight loss monthly weight loss on liquid supliment diet best weight loss diet for a 13 year old how much weight loss 5 2 diet balanced diet plan weight loss