PostgreSQL CRUD Operations using Java
Last Updated :
28 Apr, 2025
CRUD (Create, Read, Update, Delete) operations are the basic fundamentals and backbone of any SQL database system. CRUD is frequently used in database and database design cases. It simplifies security control by meeting a variety of access criteria. The CRUD acronym identifies all of the major functions that are inherent to relational databases and the applications used to manage them, which include Oracle Database, Microsoft SQL Server, MySQL, PostgreSQL, and others. In this article, we will be learning how to perform CRUD operations by using PostgreSQL database by connecting with IntelliJ ide.
Prerequisite: Latest version of Java with IntelliJ ide and PostgreSQL with PgAdmin 4.
Step 1: Install the JDBC driver
Install the JDBC driver from the given link. https://jdbc.postgresql.org/download/. You will be seeing the below window and click on 'Download' of Java 8 42.5.4 version
Step 2: Adding downloaded JDBC driver to our Java project
Open the IntelliJ ide and first of all create a new java project only if you want to keep this whole stuff separately or else no need for you can carry on your existing java project, right click on your Java project and go to 'Open Module settings'. Now you will be seeing a window just like the below image. Go to 'Libraries' and click on the '+' symbol which is on the top and then select your downloaded JDBC driver from Downloads and then click on 'apply' followed by 'Ok'.
Step 3: Create a DataBase
Open pgAdmin 4 on your PC after entering your password go to the Browser window, Right click on Databases, and create a new Database. Give the database name "newDB" only, because we are using this database in performing CRUD operations.
Step 4: Creating a Connection
Now open your IntelliJ idea and create a package of any name and a class of name of 'connection_class' in the Java project where you have added the JDBC driver otherwise it will not work. Now copy the below code in your class and don't forget to change the username and password while creating a Connection. Generally, the username is postgres by default and the password is what you have set to open pgAdmin 4.
Java
package GFG_article;
import java.sql.Connection;
import java.sql.DriverManager;
public class connection_class {
public static void main(String[] args) {
Connection con=connect_to_db("newDB","postgres","abc@123");
}
public static Connection connect_to_db(String dbname, String user, String pass)
{
Connection con_obj=null;
String url="jdbc:postgresql://localhost:5432/";
try
{
con_obj= DriverManager.getConnection(url+dbname,user,pass);
if(con_obj!=null)
{
System.out.println("Connection established successfully !");
}
else
{
System.out.println("Connection failed !!");
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
return con_obj;
}
}
After running the above code you should get the output as in the below image otherwise there is some issue and you haven't followed the above steps. Just evaluate the above steps again correctly.
Output:
Step 5: Creating a Table
Now just copy the below 'createTable' method in your existing code and call the createTable method with the below syntax which is in the main method. The table name should be a student. Here we have created 3 columns names, rollno, and dept for the student table.
Java
package GFG_article;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class connection_class {
public static void main(String[] args) {
Connection con=connect_to_db("newDB","postgres","abrar");
createTable(con,"student");
}
public static Connection connect_to_db(String dbname, String user, String pass)
{
Connection con_obj=null;
String url="jdbc:postgresql://localhost:5432/";
try
{
con_obj= DriverManager.getConnection(url+dbname,user,pass);
if(con_obj!=null)
{
System.out.println("Connection established successfully !");
}
else
{
System.out.println("Connection failed !!");
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
return con_obj;
}
public static void createTable(Connection con,String tableName)
{
Statement stmt;
try {
String query="create table "+tableName+" (name varchar(20),rollno int,dept varchar(20));";
stmt=con.createStatement();
stmt.executeUpdate(query);
System.out.println("Table has been created successfully !!");
}
catch (Exception e)
{
System.out.println("Exception caught");
}
}
}
The output after running the above program.
Output:
So the table student has been created successfully. To check whether it has been affected in postgreSql database or not, just go to pgAdmin 4 and go to Servers -> newDB -> Schemas -> Tables(1) -> student. You can find the scenario just like the below image.
Step 6: Inserting records in the student table
Now remove the createTable method from your current code and add the insertRow method as our table has been created already. Insert the records as shown in the below code of the main method with the appropriate datatype values.
Java
package GFG_article;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class connection_class {
public static void main(String[] args) {
Connection con=connect_to_db("newDB","postgres","abrar");
insertRow(con,"student","Rohit",10,"CSE");
insertRow(con,"student","Ajay",15,"ECE");
insertRow(con,"student","Kartik",6,"Mech");
insertRow(con,"student","Sam",14,"Civil");
insertRow(con,"student","John",11,"IT");
insertRow(con,"student","Rahul",4,"CST");
}
public static Connection connect_to_db(String dbname, String user, String pass)
{
Connection con_obj=null;
String url="jdbc:postgresql://localhost:5432/";
try
{
con_obj= DriverManager.getConnection(url+dbname,user,pass);
if(con_obj!=null)
{
System.out.println("Connection established successfully !");
}
else
{
System.out.println("Connection failed !!");
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
return con_obj;
}
public static void insertRow(Connection con,String tName,String name,int rno,String dept)
{
Statement stmt;
try
{
String query=String.format("insert into %s(name,rollno,dept) values('%s','%s','%s');",tName,name,rno,dept);
stmt=con.createStatement();
stmt.executeUpdate(query);
System.out.println("Inserted successfully !");
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
}
You should be getting the output just like the below image as we have inserted 6 records so far.
Output:
Now if you want to check whether the rows/records have been added to the table or not, you can go to pgAdmin 4 and then to the queries window which is present at the top of the Browser window. Now you can use the below query of select statement to access the whole table. Try it out!
Step 7: Reading the table in IntelliJ from postgres database
Now you can remove the insertRow method and add the readTable method with the below code and call the readTable from the main method as shown below.
Java
package GFG_article;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class connection_class {
public static void main(String[] args) {
Connection con=connect_to_db("newDB","postgres","abrar");
readTable(con,"student");
}
public static Connection connect_to_db(String dbname, String user, String pass)
{
Connection con_obj=null;
String url="jdbc:postgresql://localhost:5432/";
try
{
con_obj= DriverManager.getConnection(url+dbname,user,pass);
if(con_obj!=null)
{
System.out.println("Connection established successfully !");
}
else
{
System.out.println("Connection failed !!");
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
return con_obj;
}
public static void readTable(Connection con,String tName)
{
Statement stmt;
ResultSet rs;
try {
stmt=con.createStatement();
String query="select * from "+tName+";";
rs=stmt.executeQuery(query);
System.out.println("Name\t\tRollno\t\tDept");
System.out.println("---------------------------");
while(rs.next())
{
System.out.print(rs.getString("name")+"\t\t");
System.out.print(rs.getString("rollno")+"\t\t\t");
System.out.println(rs.getString("dept"));
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
}
All the records of the table should be printed like this. So far we have successfully fetched all the records from postgres database.
Output:
Step 8: Updating the Table
Now it's time to update the table record. Here I've changed the name of Sam to Virat by using the rollno column. Just add the updateRow method to the existing code and run it.
Java
package GFG_article;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class connection_class {
public static void main(String[] args) {
Connection con=connect_to_db("newDB","postgres","abrar");
updateRow(con,"student","Virat",14);
readTable(con,"student");
}
public static Connection connect_to_db(String dbname, String user, String pass)
{
Connection con_obj=null;
String url="jdbc:postgresql://localhost:5432/";
try
{
con_obj= DriverManager.getConnection(url+dbname,user,pass);
if(con_obj!=null)
{
System.out.println("Connection established successfully !");
}
else
{
System.out.println("Connection failed !!");
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
return con_obj;
}
public static void updateRow(Connection con,String tName,String newname,int rno)
{
Statement stmt;
try {
stmt=con.createStatement();
String query=String.format("update %s set name = '%s' where rollno=%d;",tName,newname,rno);
stmt.executeUpdate(query);
System.out.println("Row updated Successfully!");
} catch (Exception e) {
e.printStackTrace();
}
}
public void readTable(Connection con,String tName)
{
Statement stmt;
ResultSet rs;
try {
stmt=con.createStatement();
String query="select * from "+tName+";";
rs=stmt.executeQuery(query);
System.out.println("Name\t\tRollno\t\tDept");
System.out.println("---------------------------");
while(rs.next())
{
System.out.print(rs.getString("name")+"\t\t");
System.out.print(rs.getString("rollno")+"\t\t\t");
System.out.println(rs.getString("dept"));
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
}
So the name of Sam has been changed to Virat successfully. You can try changing whatever you want like changing the column name, rollno of student, and as well as the name of the table also by following the update query syntax rules.
Output:
Step 9: Deleting the row from Table
Now, last but not least just replace the updateRow method with deleteRow method and try calling it from the main method along with readTable to get the output as in the below image.
Java
package GFG_article;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class connection_class {
public static void main(String[] args) {
Connection con=connect_to_db("newDB","postgres","abrar");
deleteRow(con,"student","Rahul","name");
readTable(con,"student");
}
public static Connection connect_to_db(String dbname, String user, String pass)
{
Connection con_obj=null;
String url="jdbc:postgresql://localhost:5432/";
try
{
con_obj= DriverManager.getConnection(url+dbname,user,pass);
if(con_obj!=null)
{
System.out.println("Connection established successfully !");
}
else
{
System.out.println("Connection failed !!");
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
return con_obj;
}
public static void deleteRow(Connection con,String tName,String nameStud,String col)
{
Statement stmt;
try {
String query="delete from "+tName+" where name = '"+nameStud+"';";
stmt=con.createStatement();
stmt.executeUpdate(query);
System.out.println("Row deleted successfully !");
}
catch (Exception e)
{
System.out.println("Exception caught in deleteTable");
}
}
public void readTable(Connection con,String tName)
{
Statement stmt;
ResultSet rs;
try {
stmt=con.createStatement();
String query="select * from "+tName+";";
rs=stmt.executeQuery(query);
System.out.println("Name\t\tRollno\t\tDept");
System.out.println("---------------------------");
while(rs.next())
{
System.out.print(rs.getString("name")+"\t\t");
System.out.print(rs.getString("rollno")+"\t\t\t");
System.out.println(rs.getString("dept"));
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
}
Here we have deleted the record with the name 'Sam', and also check out on pgAdmin 4 whether the changes were affected in postgres database or not.
Output:
Similar Reads
Java Tutorial
Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java OOP(Object Oriented Programming) Concepts
Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Java Interview Questions and Answers
Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Arrays in Java
Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Inheritance in Java
Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Collections in Java
Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Java Exception Handling
Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Java Interface
An Interface in Java programming language is defined as an abstract type used to specify the behaviour of a class. An interface in Java is a blueprint of a behaviour. A Java interface contains static constants and abstract methods. Key Properties of Interface:The interface in Java is a mechanism to
12 min read
Java Programs - Java Programming Examples
In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read
Polymorphism in Java
Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read