Open In App

Performing Database Operations in Java | SQL CREATE, INSERT, UPDATE, DELETE and SELECT

In this article, we will be learning about how to do basic database operations using JDBC (Java Database Connectivity) API in Java programming language. These basic operations are INSERT, SELECT, UPDATE, and DELETE statements in SQL language. Although the target database system is Oracle Database, the same techniques can be applied to other database systems as well because the query syntax used is standard SQL and is generally supported by all relational database systems.

Prerequisites:

You need to go through this article before continuing for a better understanding.



java.sql Package

Before jumping into the database operation let us know about java.sql package which we will be using in our Java program for connecting to the database.

java.sql package provides APIs for data access and data processing in a relational database using Java programming language. There are some important interfaces and classes that come under java.sql package.



Interfaces

Class

Creating a user in Oracle Database and granting required permissions : 

create user  identified by ;
conn / as sysdba;
grant dba to ;

Create a sample table with blank fields : 

CREATE TABLE userid(
id varchar2(30) NOT NULL PRIMARY KEY,
pwd varchar2(30) NOT NULL,
fullname varchar2(50),
email varchar2(50)
);

Principal JDBC interfaces and classes

Let’s take an overview look at the JDBC’s main interfaces and classes which we’ll use in this article. They are all available under the java.sql package: 

Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1");

Statement stmt = con.createStatement();
String q1 = "insert into userid values
('" +id+ "', '" +pwd+ "', '" +fullname+ "', '" +email+ "')";
int x = stmt.executeUpdate(q1);

Statement stmt = con.createStatement();
String q1 = "select * from userid WHERE id = '" + id + "'
AND pwd = '" + pwd + "'";
ResultSet rs = stmt.executeQuery(q1);

Connecting to the Database

The Oracle Database server listens on the default port 1521 at localhost. The following code snippet connects to the database name userid by the user login1 and password pwd1.




// Java program to illustrate
// Connecting to the Database
import java.sql.*;
 
public class connect
{
    public static void main(String args[])
    {
        try
        {
            Class.forName("oracle.jdbc.driver.OracleDriver");
             
            // Establishing Connection
            Connection con = DriverManager.getConnection(
             "jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1");
 
            if (con != null)            
                System.out.println("Connected");           
            else           
                System.out.println("Not Connected");
             
            con.close();
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
    }
}

Output :
Connected

Note: Here oracle in database URL in getConnection() method specifies SID of Oracle Database. For Oracle database 11g it is orcl and for oracle database 10g it is xe.

1. Implementing Insert Statement:




// Java program to illustrate
// inserting to the Database
import java.sql.*;
 
public class insert1
{
    public static void main(String args[])
    {
        String id = "id1";
        String pwd = "pwd1";
        String fullname = "geeks for geeks";
        String email = "geeks@geeks.org";
         
        try
        {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection con = DriverManager.getConnection("
             jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1");
            Statement stmt = con.createStatement();
             
            // Inserting data in database
            String q1 = "insert into userid values('" +id+ "', '" +pwd+
                                  "', '" +fullname+ "', '" +email+ "')";
            int x = stmt.executeUpdate(q1);
            if (x > 0)           
                System.out.println("Successfully Inserted");           
            else           
                System.out.println("Insert Failed");
             
            con.close();
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
    }
}

Output :
Successfully Registered

2. Implementing Update Statement:




// Java program to illustrate
// updating the Database
import java.sql.*;
 
public class update1
{
    public static void main(String args[])
    {
        String id = "id1";
        String pwd = "pwd1";
        String newPwd = "newpwd";
        try
        {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection con = DriverManager.getConnection("
             jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1");
            Statement stmt = con.createStatement();
         
            // Updating database
            String q1 = "UPDATE userid set pwd = '" + newPwd +
                    "' WHERE id = '" +id+ "' AND pwd = '" + pwd + "'";
            int x = stmt.executeUpdate(q1);
             
            if (x > 0)           
                System.out.println("Password Successfully Updated");           
            else           
                System.out.println("ERROR OCCURRED :(");
             
            con.close();
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
    }
}

Output :
Password Successfully Updated

3. Implementing Delete Statement:




// Java program to illustrate
// deleting from Database
import java.sql.*;
 
public class delete
{
    public static void main(String args[])
    {
        String id = "id2";
        String pwd = "pwd2";
        try
        {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection con = DriverManager.getConnection("
             jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1");
            Statement stmt = con.createStatement();
                  
            // Deleting from database
            String q1 = "DELETE from userid WHERE id = '" + id +
                    "' AND pwd = '" + pwd + "'";
                     
            int x = stmt.executeUpdate(q1);
             
            if (x > 0)           
                System.out.println("One User Successfully Deleted");           
            else
                System.out.println("ERROR OCCURRED :("); 
           
            con.close();
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
    }
}

Output :
One User Successfully Deleted

4. Implementing Select Statement:




// Java program to illustrate
// selecting from Database
import java.sql.*;
 
public class select
{
    public static void main(String args[])
    {
        String id = "id1";
        String pwd = "pwd1";
        try
        {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection con = DriverManager.getConnection("
                    jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1");
            Statement stmt = con.createStatement();
             
            // SELECT query
            String q1 = "select * from userid WHERE id = '" + id +
                                    "' AND pwd = '" + pwd + "'";
            ResultSet rs = stmt.executeQuery(q1);
            if (rs.next())
            {
                System.out.println("User-Id : " + rs.getString(1));
                System.out.println("Full Name :" + rs.getString(3));
                System.out.println("E-mail :" + rs.getString(4));
            }
            else
            {
                System.out.println("No such user id is already registered");
            }
            con.close();
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
    }
}

Output 
User-Id : id1
Full Name : geeks for geeks
E-mail :geeks@geeks.org

Note : Here the column index is 1-based, the first column will be at index 1, the second at index 2, and so on. 

For other data types, the ResultSet provide appropriate getter methods:


Article Tags :