The Wayback Machine - https://web.archive.org/web/20240921071827/https://www.geeksforgeeks.org/performing-database-operations-java-sql-create-insert-update-delete-select/
Open In App

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

Last Updated : 17 Nov, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

  • Connection
  • Statement
  • PreparedStatement
  • CallableStatement
  • ResultSet
  • ResultSetMetaData

Class

  • DriverManager class

Creating a user in Oracle Database and granting required permissions : 

  • Open oracle using cmd. For that type sqlplus in cmd and press Enter.
  • Create a user-id protected by a password. This user-id is called child user. 
create user  identified by ;
  • Grant required permissions to child user. For simplicity we grant database administrator privilege to child user. 
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() : Here we load the driver’s class file into memory at the runtime. No need of using new or creation of object. 
Class.forName("oracle.jdbc.driver.OracleDriver");
  • DriverManager: This class is used to register driver for a specific database type (e.g. Oracle Database in this tutorial) and to establish a database connection with the server via its getConnection() method.
  • Connection: This interface represents an established database connection (session) from which we can create statements to execute queries and retrieve results, get metadata about the database, close connection, etc. 
Connection con = DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1");

  • Statement and PreparedStatement: These interfaces are used to execute static SQL query and parameterized SQL query, respectively. Statement is the super interface of the PreparedStatement interface. Their commonly used methods are:
    1. boolean execute(String sql): executes a general SQL statement. It returns true if the query returns a ResultSet, false if the query returns an update count or returns nothing. This method can be used with a Statement only.
    2. int executeUpdate(String sql): executes an INSERT, UPDATE or DELETE statement and returns an update account indicating number of rows affected (e.g. 1 row inserted, or 2 rows updated, or 0 rows affected). 
Statement stmt = con.createStatement();
String q1 = "insert into userid values
('" +id+ "', '" +pwd+ "', '" +fullname+ "', '" +email+ "')";
int x = stmt.executeUpdate(q1);

  • ResultSet executeQuery(String sql): executes a SELECT statement and returns a ResultSet object which contains results returned by the query. 
Statement stmt = con.createStatement();
String q1 = "select * from userid WHERE id = '" + id + "'
AND pwd = '" + pwd + "'";
ResultSet rs = stmt.executeQuery(q1);

  • ResultSet: contains table data returned by a SELECT query. Use this object to iterate over rows in the result set using next() method.
  • SQLException: this checked exception is declared to be thrown by all the above methods, so we have to catch this exception explicitly when calling the above classes’ methods.

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




// 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




// 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




// 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




// 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




// 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:

  • getString()
  • getInt()
  • getFloat()
  • getDate()
  • getTimestamp()



Similar Reads

Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
How to Update Multiple Columns in Single Update Statement in SQL?
In this article, we will see, how to update multiple columns in a single statement in SQL. We can update multiple columns by specifying multiple columns after the SET command in the UPDATE statement. The UPDATE statement is always followed by the SET command, it specifies the column where the update is required. UPDATE for Multiple ColumnsSyntax: U
3 min read
SQL INSERT INTO SELECT Statement
In SQL, the INSERT INTO statement is used to add or insert records to the specified table. We can use this statement to add data directly to the table. We use the VALUES keyword along with the INSERT INTO statement. VALUES keyword is accompanied by column names in a specific order in which we want to insert values in them. SELECT statement is used
5 min read
Insert Into Select statement in MS SQL Server
The INSERT INTO SELECT statement in SQL Server is a versatile feature that enables you to efficiently copy data from one or more tables into another table. This functionality is essential for tasks such as data transfer, backup creation, and data merging. In this article, We will learn to Insert Into Select statement in MS SQL Server by understandi
4 min read
SQL Select Database
The USE DATABASE statement is a command in certain SQL-based database management systems that allows users to select and set a specific database as the default for the current session. By selecting a database, subsequent queries are executed within the context of that database, making it easier to interact with tables and other objects contained wi
3 min read
Delete Database in MS SQL Server
Prerequisite – Introduction of MS SQL Server and Create Database in MS SQL Server System databases can't be deleted, only user databases could be deleted. Data and log files will automatically be deleted from disk with database deletion. To delete a database, the below methods could be used – SQL Server Management Studio. Transact-SQL. These are ex
1 min read
BULK INSERT in SQL Server(T-SQL command)
BULK INSERT in SQL Server(T-SQL command): In this article, we will cover bulk insert data from csv file using the T-SQL command in the SQL server and the way it is more useful and more convenient to perform such kind of operations. Let's discuss it one by one.  ConditionSometimes there is a scenario when we have to perform bulk insert data from .cs
3 min read
SQL - SELECT from Multiple Tables with MS SQL Server
In SQL we can retrieve data from multiple tables also by using SELECT with multiple tables which actually results in CROSS JOIN of all the tables. The resulting table occurring from CROSS JOIN of two contains all the row combinations of the 2nd table which is a Cartesian product of tables. If we consider table1 contains m rows and table2 contains n
3 min read
How to SQL Select from Stored Procedure using SQL Server?
There may be situations in SQL Server where you need to use a stored procedure to get data from a SQL query. For direct data selection from a stored procedure within a query, SQL Server offers options like OPENQUERY and OPENROWSET. The usual way is running the stored procedure independently and then querying the outcomes. The idea of utilizing SQL
3 min read
MySQL INSERT ON DUPLICATE KEY UPDATE Statement
MySQL INSERT ON DUPLICATE KEY UPDATE statement is an extension to the INSERT statement, that if the row being inserted already exists in the table, it will perform a UPDATE operation instead. INSERT ON DUPLICATE KEY UPDATE in MySQLINSERT ON DUPLICATE KEY UPDATE statement in MySQL is used to handle duplicate entries on a primary key or unique column
3 min read
Difference between Structured Query Language (SQL) and Transact-SQL (T-SQL)
Structured Query Language (SQL): Structured Query Language (SQL) has a specific design motive for defining, accessing and changement of data. It is considered as non-procedural, In that case the important elements and its results are first specified without taking care of the how they are computed. It is implemented over the database which is drive
2 min read
Find lexicographical smallest string by performing the given operations N times
Given a string S of N characters, the task is to find the smallest lexicographical string after performing each of the following operations N times in any order: Remove the 1st character of S and insert it into a stack X.Remove the top of stack X and append it to the end of another string Y which is initially empty. Example: Input: S = "cab"Output:
8 min read
SQL CREATE DATABASE
SQL CREATE DATABASE statement creates a new database in SQL-based DBMS. CREATE DATABASE in SQLThe CREATE DATABASE query in SQL is used to create a new database in the database management system. It is also used in MySQL and other relational database management systems (RDBMS) to create databases. SyntaxThe syntax to use the CREATE DATABASE command
2 min read
Create Database in MS SQL Server
Databases in Microsoft SQL Server are crucial for managing data, categorized into system databases, which are auto-created and user databases, created by users. In this article, We will learn about the basics of system and user databases along with methods for creating and managing them using T-SQL and SQL Server Management Studio (SSMS). Create Da
6 min read
How to Update Data to SQLite Database in Android?
We have seen How to Create and Add Data to SQLite Database in Android as well as How to Read Data from SQLite Database in Android. We have performed different SQL queries for reading and writing our data to SQLite database. In this article, we will take a look at updating data to SQLite database in Android. What we are going to build in this articl
10 min read
How to Update Data in Back4App Database in Android?
In the previous article, we have seen adding as well as reading data from our Bac4App database in the Android app. In this article, we will take a look at Updating this data in your database. What we are going to build in this article? We will be building a simple application in which we will be updating the previously added data in our Back4App da
7 min read
How to Update Data in Realm Database in Android?
In previous articles, we have seen adding and reading data from our realm database in Android. In that article, we were adding course details in our database and reading the data in the form of a list. In this article, we will take a look at updating this data in our android app. What we are going to build in this article? We will be working on the
7 min read
Configure SQL Jobs in SQL Server using T-SQL
In this article, we will learn how to configure SQL jobs in SQL Server using T-SQL. Also, we will discuss the parameters of SQL jobs in SQL Server using T-SQL in detail. Let's discuss it one by one. Introduction :SQL Server Agent is a component used for database task automation. For Example, If we need to perform index maintenance on Production ser
7 min read
How to Insert JSON data into MySQL database using PHP?
To insert JSON data into MySQL database using PHP, use the json_decode function in PHP to convert JSON object into an array that can be inserted into the database. Here, we are going to see how to insert JSON data into MySQL database using PHP through the XAMPP server in a step-by-step way. JSON Structure:[{ "data1": "value1", "data2": "value2", .
3 min read
Difference Between ON DELETE CASCADE and ON DELETE SET NULL in DBMS
The phrases "ON DELETE CASCADE" and "ON DELETE SET NULL" refer to options that can be specified when defining foreign key constraints in relational databases. These options determine the behavior of the database system when a record in the parent table (referenced table) is deleted. Let's explore each option: What is ON DELETE CASCADE?When you spec
5 min read
Difference between ALTER and UPDATE Command in SQL
1. ALTER Command: ALTER SQL command is a DDL (Data Definition Language) statement. ALTER is used to update the structure of the table in the database (like add, delete, modify the attributes of the tables in the database). Syntax: // add a column to the existing table ALTER TABLE tableName ADD columnName columnDefinition; // drop a column from the
3 min read
How to Delete Data in SQLite Database in Android?
In the previous articles, we have seen three operations of CRUD operations such as create, read and update operations in our Android app. In this article, we will take a look at adding delete operation for deleting our items stored in the SQLite database. What we are going to build in this article? We will be building a simple application in which
8 min read
How to Delete Data in Back4App Database in Android?
We have seen adding data to our Back4App database along with reading and updating this data. In this article, we will take a look at Deleting this data. What we are going to build? We will be adding a simple button inside our update screen where we were updating our data and inside that screen, we will be adding a new button for deleting the course
7 min read
How to Delete Data in Realm Database in Android?
In the previous series of articles on the realm database, we have seen adding, reading, and updating data using the realm database in android. In that articles, we were adding course details, reading them, and updating them. In this article, we will take a look at deleting these course details from our realm database in the Android app. What we are
6 min read
How to Delete Data from Firebase Realtime Database in Android?
In this article, we will see How to Delete added data inside our Firebase Realtime Database. So we will move towards the implementation of this deleting data in Android Firebase. What we are going to build in this article? We will be showing a simple AlertBox when the user long clicks on the item of RecyclerView. It will have two options. (Delete a
4 min read
How to Delete Duplicate Records in Oracle Database?
To delete the duplicate record in the Oracle database, first find all distinct records and then delete the remaining rows using the row_id, as it is the physical address of that row and is different for each row. Here we will see, how to delete duplicate records in Oracle. Delete Duplicate Records in the Oracle DatabaseLet's look at an example wher
1 min read
How to pre populate database in Android using SQLite Database
Introduction : Often, there is a need to initiate an Android app with an already existing database. This is called prepopulating a database. In this article, we will see how to pre-populate database in Android using SQLite Database. The database used in this example can be downloaded as Demo Database. To prepopulate a SQLite database in an Android
7 min read
Count of operations required to update the array such that it satisfies the given conditions
Given an array arr[] of size N and an integer K. The task is to find the operations required to update the array such that it is possible to move from index 0 to index N - 1 when any index j can be visited from index i if index j is adjacent to index i and abs(arr[i] - arr[j]) ? K. In a single operation, any element of the array can be incremented
6 min read
SQL Query to select Data from Tables Using Join and Where
The aim of this article is to make a simple program to Join two tables using Join and Where clause using MySQL. Below is the method to do the same using MySQL. The prerequisites of this article are MySQL and Apache Server on your computer are installed. What is a Query in SQL? A SQL query is a request passed for data/information from a table in a d
3 min read
How to Select Data Between Two Dates and Times in SQL Server?
In SQL, some transactions need to be extracted based on their completion times and dates. Here, the DATETIME2 data type in SQL to perform such operations. For this article, we will be using the Microsoft SQL Server as our database. Note: Here, we will use the two dates and times given in the query and separate them using the BETWEEN keyword. This i
2 min read
Article Tags :
Practice Tags :