English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

PostgreSQL JAVA Interface

Installation

Start using PostgreSQL in our Java program Before that, we need to make sure that PostgreSQL JDBC and Java are set up on the machine. You can check Java Tutorial, to learn how to install Java. Now let's check how to set up the postgresqljdbc driver.

  • Download the latest version of postgresql from the following address-(version).jdbc.jar postgresql-jdbc Download.

  • Add the downloaded jar file postgresql-(VERSION).jar, or you can use it with-The classpath option is used together, as shown in the following example.

The following part assumes that you are familiar with the javajdbc concept. If not, it is recommended that you spend half an hour learning the JDBC tutorial to get familiar with the concepts explained below.

Connect to the database

The following Java code demonstrates how to connect to an existing database. If the database does not exist, it will be created, and finally, a database object will be returned.

import java.sql.Connection;
import java.sql.DriverManager;
public class PostgreSQLJDBC {
   public static void main(String args[]) {
      Connection c = null;
      try {
         Class.forName("org.postgresql.Driver");
         c = DriverManager
            .getConnection("jdbc:postgresql:")//localhost:5432/testdb",
            "postgres", ""123");
      } catch (Exception e) {
         e.printStackTrace();
         System.err.println(e.getClass().getName())+: "+e.getMessage());
         System.exit(0);
      }
      System.out.println("Opened database successfully");
   }
}

Before compiling and running the above program, please find the pg_hba.conf file in the PostgreSQL installation directory, create a file, and add the following lines:

# IPv4 local connections:
host all all         127.0.0.1/32          md5

If the postgres server is not running, you can use the following command to start it/Restart the postgres server:

Now, let's compile and run the above program to connect to testdb. Here, we use postgres as the user ID 123Use it as a password to access the database. You can change it according to the database configuration and settings. We also assume that the current version of the JDBC driver is postgresql-9.2-1002.jdbc3.jar is available in the current directory.

C:\JavaPostgresIntegration>javac PostgreSQLJDBC.java
C:\JavaPostgresIntegration>java -cp c:\tools\postgresql-9.2-1002.jdbc3.jar;C:\JavaPostgresIntegration PostgresQLJDBC
Database opened successfully

Create table

The following Java program will be used to create a table in the previously opened database. Please make sure that there is no such table in the target database.

import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class PostgreSQLJDBC {
   public static void main(String args[]) {
      Connection c = null;
      Statement stmt = null;
      try {
         Class.forName("org.postgresql.Driver");
         c = DriverManager
            .getConnection("jdbc:postgresql:")//localhost:5432/testdb",
            "manisha", "123");
         System.out.println("Opened database successfully");
         stmt = c.createStatement();
         String sql = "CREATE TABLE COMPANY " +
            " (ID INT PRIMARY KEY NOT NULL," +
            " NAME TEXT NOT NULL, " +
            " AGE INT NOT NULL, " +
            " ADDRESS CHAR("50), ";" +
            " SALARY REAL);"
         stmt.executeUpdate(sql);
         stmt.close();
         c.close();
      } catch (Exception e) {
         System.err.println(e.getClass().getName());+: "+ e.getMessage());
         System.exit(0);
      }
      System.out.println("Table created successfully");
   }
}

When compiling and executing the program, it will create the COMPANY table in the testdb database and display the following two lines-

Database opened successfully
Table created successfully

INSERT Operation

The following Java program demonstrates how to create records in the COMPANY table created in the above example-

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class PostgreSQLJDBC {
   public static void main(String args[]) {
      Connection c = null;
      Statement stmt = null;
      try {
         Class.forName("org.postgresql.Driver");
         c = DriverManager
            .getConnection("jdbc:postgresql:")//localhost:5432/testdb",
            "manisha", "123");
         c.setAutoCommit(false);
         System.out.println("Opened database successfully");
         stmt = c.createStatement();
         String sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) "
            + "VALUES (1, 'Paul', 32, 'California', 20000.00 );";
         stmt.executeUpdate(sql);
         sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) "
            + "VALUES (2, 'Allen', 25, 'Texas', 15000.00 );";
         stmt.executeUpdate(sql);
         sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) "
            + "VALUES (3, 'Teddy', 23, 'Norway', 20000.00 );";
         stmt.executeUpdate(sql);
         sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) "
            + "VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 );";
         stmt.executeUpdate(sql);
         stmt.close();
         c.commit();
         c.close();
      } catch (Exception e) {
         System.err.println(e.getClass().getName());+: "+ e.getMessage());
         System.exit(0);
      }
      System.out.println("Records created successfully");
   }
}

When compiling and executing the above program, it will create the given records in the COMPANY table and display the following two lines-

Database opened successfully
Records created successfully

SELECT Operation

The following Java program demonstrates how we retrieve and display records from the COMPANY table created in the above example

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class PostgreSQLJDBC {
   public static void main(String args[]) {
      Connection c = null;
      Statement stmt = null;
      try {
         Class.forName("org.postgresql.Driver");
         c = DriverManager
            .getConnection("jdbc:postgresql:")//localhost:5432/testdb",
            "manisha", "123");
         c.setAutoCommit(false);
         System.out.println("Opened database successfully");
         stmt = c.createStatement();
         ResultSet rs = stmt.executeQuery("SELECT"} * FROM COMPANY; ");
         while (rs.next()) {
            int id = rs.getInt("id");
            String name = rs.getString("name");
            int age = rs.getInt("age");
            String address = rs.getString("address");
            float salary = rs.getFloat("salary");
            System.out.println("ID = "); + id);
            System.out.println("NAME = "); + name);
            System.out.println("AGE = "); + age);
            System.out.println("ADDRESS = "); + address);
            System.out.println("SALARY = "); + salary);
            System.out.println();
         }
         rs.close();
         stmt.close();
         c.close();
      } catch (Exception e) {
         System.err.println(e.getClass().getName());+: "+ e.getMessage());
         System.exit(0);
      }
      System.out.println("Operation completed successfully");
   }
}

When the program is compiled and executed, the following results are produced

Database opened successfully
ID = 1
NAME = Paul
AGE = 32
ADDRESS = California
SALARY = 20000.0
ID = 2
NAME = Allen
AGE = 25
ADDRESS = Texas
SALARY = 15000.0
ID = 3
NAME = Teddy
AGE = 23
ADDRESS = Norway
SALARY = 20000.0
ID = 4
NAME = Mark
AGE = 25
ADDRESS = Rich-Mond
SALARY = 65000.0
Operation completed successfully

UPDATE Operation

The following Java code demonstrates how to use the UPDATE statement to update any record and then retrieve and display the updated records from our COMPANY table

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class PostgreSQLJDBC {
   public static void main(String args[]) {
      Connection c = null;
      Statement stmt = null;
      try {
         Class.forName("org.postgresql.Driver");
         c = DriverManager
            .getConnection("jdbc:postgresql:")//localhost:5432/testdb",
            "manisha", "123");
         c.setAutoCommit(false);
         System.out.println("Opened database successfully");
         stmt = c.createStatement();
         String sql = "UPDATE COMPANY set SALARY =" 25000.00 where ID=1;";
         stmt.executeUpdate(sql);
         c.commit();
         ResultSet rs = stmt.executeQuery("SELECT"} * FROM COMPANY; ");
         while (rs.next()) {
            int id = rs.getInt("id");
            String name = rs.getString("name");
            int age = rs.getInt("age");
            String address = rs.getString("address");
            float salary = rs.getFloat("salary");
            System.out.println("ID = "); + id);
            System.out.println("NAME = "); + name);
            System.out.println("AGE = "); + age);
            System.out.println("ADDRESS = "); + address);
            System.out.println("SALARY = "); + salary);
            System.out.println();
         }
         rs.close();
         stmt.close();
         c.close();
      } catch (Exception e) {
         System.err.println(e.getClass().getName());+: "+ e.getMessage());
         System.exit(0);
      }
      System.out.println("Operation completed successfully");
   }
}

When the program is compiled and executed, the following results are produced

Database opened successfully
ID = 2
NAME = Allen
AGE = 25
ADDRESS = Texas
SALARY = 15000.0
ID = 3
NAME = Teddy
AGE = 23
ADDRESS = Norway
SALARY = 20000.0
ID = 4
NAME = Mark
AGE = 25
ADDRESS = Rich-Mond
SALARY = 65000.0
ID = 1
NAME = Paul
AGE = 32
ADDRESS = California
SALARY = 25000.0
Operation completed successfully

DELETE Operation

The following Java code demonstrates how to use the DELETE statement to delete any record and then retrieve and display the remaining records from our COMPANY table

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class PostgreSQLJDBC6 {
   public static void main(String args[]) {
      Connection c = null;
      Statement stmt = null;
      try {
         Class.forName("org.postgresql.Driver");
         c = DriverManager
            .getConnection("jdbc:postgresql:")//localhost:5432/testdb",
            "manisha", "123");
         c.setAutoCommit(false);
         System.out.println("Opened database successfully");
         stmt = c.createStatement();
         String sql = "DELETE from COMPANY where ID =" 2;";
         stmt.executeUpdate(sql);
         c.commit();
         ResultSet rs = stmt.executeQuery("SELECT"} * FROM COMPANY; ");
         while (rs.next()) {
            int id = rs.getInt("id");
            String name = rs.getString("name");
            int age = rs.getInt("age");
            String address = rs.getString("address");
            float salary = rs.getFloat("salary");
            System.out.println("ID = "); + id);
            System.out.println("NAME = "); + name);
            System.out.println("AGE = "); + age);
            System.out.println("ADDRESS = "); + address);
            System.out.println("SALARY = "); + salary);
            System.out.println();
         }
         rs.close();
         stmt.close();
         c.close();
      } catch (Exception e) {
         System.err.println(e.getClass().getName());+: "+ e.getMessage());
         System.exit(0);
      }
      System.out.println("Operation completed successfully");
   }
}

When the program is compiled and executed, the following results are produced

Database opened successfully
ID = 3
NAME = Teddy
AGE = 23
ADDRESS = Norway
SALARY = 20000.0
ID = 4
NAME = Mark
AGE = 25
ADDRESS = Rich-Mond
SALARY = 65000.0
ID = 1
NAME = Paul
AGE = 32
ADDRESS = California
SALARY = 25000.0
Operation completed successfully