Tuesday, November 19, 2024
Google search engine
HomeLanguagesJavaPostgreSQL CRUD Operations using Java

PostgreSQL CRUD Operations using Java

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: 

 

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments