Performing Database Operations in Java | SQL CREATE, INSERT, UPDATE, DELETE and SELECT
Last Updated :
17 Nov, 2023
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
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:
- 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.
- 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 = "[email protected]";
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 :[email protected]
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
Performing DataBase Operations in XAMPP
XAMPP is a cross-platform web server used to develop and test programs on a local server. It is developed and managed by Apache Friends and is open-source. It has an Apache HTTP Server, MariaDB, and interpreter for 11 different programming languages like Perl and PHP. XAMPP Stands for cross-platform
3 min read
CRUD Operation in MySQL Using PHP, Volley Android - Insert Data
It is known that we can use MySQL to use Structure Query Language to store the data in the form of RDBMS. SQL is the most popular language for adding, accessing and managing content in a database. It is most noted for its quick processing, proven reliability, ease, and flexibility of use. The applic
10 min read
Spring - Perform Update Operation in CRUD
CRUD (Create, Read, Update, Delete) operations are the building block for developers stepping into the software industry. CRUD is mostly simple and straight forward except that real-time scenarios tend to get complex. Among CRUD operations, the update operation requires more effort to get right comp
13 min read
Java Servlet and JDBC Example | Insert data in MySQL
Prerequisites: Servlet, JDBC Connectivity To start with interfacing Java Servlet Program with JDBC Connection: Proper JDBC Environment should set-up along with database creation. To do so, download the mysql-connector.jar file from the internet, As it is downloaded, move the jar file to the apache-t
4 min read
Oracle DataBase - Grant Privileges to a User in SQL Command Line
Oracle Database is a robust and widely utilized relational database management system (RDBMS) recognized for its scalability, advanced features and performance optimization. Its architecture supports complex queries and large datasets also making it a popular choice for organizations of all sizes. I
4 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?
8 min read
How to Execute Multiple SQL Commands on a Database Simultaneously in JDBC?
Java Database Connectivity also is known as JDBC is an application programming interface in Java that is used to establish connectivity between a Java application and database. JDBC commands can be used to perform SQL operations from the Java application. Demonstrating execution of multiple SQL comm
6 min read
Spring Hibernate Configuration and Create a Table in Database
Spring Boot and Hibernate are a powerful combination for building scalable and efficient database-driven applications. Spring Boot simplifies application development by reducing boilerplate code, while Hibernate, a popular ORM (Object-Relational Mapping) framework, enables easy database interactions
4 min read
CRUD Operations in Student Management System in Java
CRUD stands for Create, Read/Retrieve, Update and Delete and these are the four basic operations that we perform on persistence storage. CRUD is data-oriented and the standardized use of HTTP methods. HTTP has a few methods which work as CRUD operations and do note they are very vital from a develop
7 min read
Understanding and Preventing SQL Injection in Java Applications
In the world of web applications and databases, security is paramount. SQL injection is a common and dangerous vulnerability that can compromise your application's integrity. In this article, we will delve into the fundamentals of SQL injection, understand how it works, and learn how to protect your
5 min read