×

Resultset in java

Resultset:

A result set is an interface that is present in the package java.sql and the resultset is used to store the data that are returned from the database table after executing the SQL statements.

 The object of the resultset is used to maintain the cursor point at the result data. By default, the first row of the resultset will be pointed by the cursor.

Resultset types:

1. Forward Only (ResultSet.TYPE_FORWARD_ONLY)

This type of result set is used to move in the form of a forwarding direction that is from the first row to the last row. By using the next () method we can forward the resultset.

Statement stmt = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery("select * from tbluser");

2. Scroll Insensitive (ResultSet.TYPE_SCROLL_INSENSITIVE)

This type of result set is used to scroll both in forwarding and backward directions and it is also can be scrolled to absolute positions by using the absolute() method. It does not change the sensitive data.

Statement stmt = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery("select * from tbluser");

3.Scroll Sensitive (ResultSet.TYPE_SCROLL_SENSITIVE)

This type of result set is used to scroll both in forwarding and backward directions and it is also can be scrolled to absolute positions by using the absolute() method. It is used to change sensitive data.

Statement stmt = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery("select * from tbluser");

Resultset concurrency:

Read Only (ResultSet.CONCUR_READ_ONLY)

This is the default concurrency model.  We can only perform Read-Only operations on ResultSet Instance. No update operations are allowed in this read-only.

Updatable (ResultSet.CONCUR_UPDATABLE)

we can perform update operations on the ResultSet instance.

Resultset example:

package com.journaldev.examples;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Date;
/**
* Java Resultset Example of Retrieving information.
* 
* @author Rahul
*
*/
public class ResultSetDemo {
public static void main(String[] args) {
String query = "select sid, firstname, lastname, dob from student";
Connection conn = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/empdb", "root", "root");
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
Integer empId = rs.getInt(1);
String firstName = rs.getString(2);
String lastName = rs.getString(3);
Date dob = rs.getDate(4);
System.out.println("SId:" + SId);
System.out.println("firstName:" + firstName);
System.out.println("lastName:" + lastName);
System.out.println("dob:" + dob);
System.out.println("");
}
rs.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
stmt.close();
conn.close();
} catch (Exception e) {}
}
}
}

Output:

empId:101
firstName:Ravi
lastName:Krishna
dob:20-04-1999
empId:102
firstName:Hari
lastName:Ram
dob:22-02-1989
empId:3
firstName:Harish
lastName:Rao
dob:25-03-1000

Resultset methods:

public boolean next():It is used to move the cursor to the one row next to the starting position.
 public boolean previous():It is used to move the cursor from the one row previous to the starting position.
public boolean first():It is used to move the pointer to the first row in the result set object.
public boolean last():It is used to move the pointer to the last row in the result set object.
public boolean absolute(int row):It is used to move the pointer to the particular row number in the ResultSet object.
public boolean relative(int row):It is used to move the pointer to the relative row number in the ResultSet object, it may be positive or negative.
public int getInt(int columnIndex):It is used to return the data of the particular column index of the starting row as int.
 public int getInt(String columnName):It is used to return the data of the particular column name of the starting row as int.
public String getString(int columnIndex):It is used to return the data of the particular column index of the starting row as String.
public String getString(String columnName):It is used to return the data of the particular column name of the starting row as String.

Example:

package com.STH.JDBC;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class ResultSet_Example { 
public static void main(String[] args) throws ClassNotFoundException {
// to do the Auto-generated method stub
//Select the query as
String select_query = "select * from student";
Class.forName("oracle.jdbc.driver.OracleDriver"); 
//Connecting to Oracle DB
try(Connection conn =
DriverManager.getConnection("jdbc:oracle:thin:system/pass123@localhost:1521:X
E"))
{
//Creating DatabaseMetaData object
DatabaseMetaData dbmd = conn.getMetaData();
boolean isSupportResultSetType = 
dbmd.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
if(isSupportResultSetType == true)
{
// Creating prepared Statement
PreparedStatement pstatemnt1 = 
conn.prepareStatement(select_query,ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.
CONCUR_UPDATABLE);
ResultSet rs = pstatemnt1.executeQuery();
//Moving the cursor to point the first row
rs.first();
System.out.println("FIRST ROW \n  STUDENT NUM = " + 
rs.getInt("SNum") + "\n LAST NAME = "+ rs.getString(2)+"\n FIRST NAME = " + rs.getString(3));
//Moving the cursor to point the last row 
rs.last();
System.out.println("LAST ROW \n STUDENT NUM = " +
rs.getInt("SNum") + "\n LAST NAME = "+ rs.getString(2)+"\n FIRST NAME = " + rs.getString(3));
//Moving the cursor to point the before the first row
rs.beforeFirst();
System.out.println("Cursor is pointing at before the
first row. Use next() to move in forward direction");
//Moving the cursor to point the first row using next() 
rs.next();
System.out.println("FIRST ROW \n EMP NUM = " +
rs.getInt("SNum") + "\n LAST NAME = "+ rs.getString(2)+"\n FIRST NAME = " + rs.getString(3));
//Moving the cursor to point the after last row 
rs.afterLast();
System.out.println("Cursor is pointing at after the last row. Use previous() to move in backward direction");
//Moving the cursor to point the last row using previous() 
rs.previous();
System.out.println("LAST ROW \n student NUM = " + 
rs.getInt("SNum") + "\n LAST NAME = "+ rs.getString(2)+"\n FIRST NAME = " + rs.getString(3));
//Moving the cursor to point the third row 
rs.absolute(3);
System.out.println("Cursor is pointing at 3rd row");
System.out.println("THIRD ROW \n student NUM = " +
rs.getInt("SNum") + "\n LAST NAME = "+ rs.getString(2)+"\n FIRST NAME = " + rs.getString(3));
//Moving the cursor to point the previous row of third row 
rs.relative(-1);
System.out.println("Cursor is pointing to the 1 row previous to the 3rd row");
System.out.println("Second ROW \n student NUM = " + rs.getInt("SNum") + "\n LAST NAME = "+
rs.getString(2)+"\n FIRST NAME = " + 
rs.getString(3));
//Moving the cursor to point the 4th row after the 2nd row 
rs.relative(4);
System.out.println("Cursor is pointing to the 4th row after the 2nd row");
System.out.println("SIXTH ROW \n STUDENT NUM = " +
rs.getInt("SNum") + "\n LAST NAME = "+ rs.getString(2)+"\n FIRST NAME = " + rs.getString(3));
//Moving the cursor to point the current row 
System.out.println(" Current Row = " + rs.getRow());


}
catch (SQLException e) {
e.printStackTrace();
}
}
}

Output:

Data in the STUDENT table.

Related Topics

Java Control Statements

Control Statements: Control statements in Java can also be referred to as decision-making while dealing with different problems. Control statements are helpful to sort out the flow of the program or...

7 minutes read.

Java Strings

String class is the most used class in Java programming language. The string is the sequence of characters, which is treated as objects in Java. Creating String objects We create String objects...

5 minutes read.

Java Program to Print Permutations of String

A string is given and you need to print all the possible ways for that string. Permutation is arranging the characters of a string to get outputs from the given...

3 minutes read.

Bouncy Number in Java

We will define bouncy numbers in this section and write Java programmes to determine whether a specific number is bouncy. Java coding exams and academic assignments usually inquire about the...

3 minutes read.

Count of Range Sum Problem in Java

In this article, we will discuss the basic approach or native approach used to count range sum problem in java. To solve this problem, we will check for numbers if they...

6 minutes read.

Java String substring() method

Java String substring() method returns a part of the String. Syntax: public String substring(int startIndex) public String substring(int startIndex, int endIndex) Parameters: startIndex : starting index endIndex : ending index Returns: It returns a specified String. Throws: StringIndexOutOfBoundsException if start...

2 minutes read.

Package naming convention in Java

It is conceivable that many programmers will use the same name for various types, given that Java programmers from all over the world create classes and interfaces. For illustration, suppose...

4 minutes read.

Star Program in Java

By solving the patterns, we can develop our coding skills and logical thinking. Mostly each pattern program uses two or more loops. Loops' number depends on the complexity of logic....

3 minutes read.

Java 16

Java 16 is the most recent short-term incremental release, based on Java 15, and it was released on March 16, 2021. Records and sealed classes are just two of the...

11 minutes read.

Objects and Classes in Java

Objects and Classes in Java Classes and objects are the basic concepts of object-oriented programming. It revolves around the real world entity. In Java, the object is a physical and logical...

5 minutes read.

Array and String based questions in Java

1. What is an Array in Java? A collection of identical data types is referred to as an array. There can be no separate data kinds. It supports the storage of...

4 minutes read.

Java gc()

Garbage collection Java language provides different ways to perform the task of memory management. In Java, objects are declared and assigned references. Once lifeof an object is completed it is dereferenced...

4 minutes read.

Graphics Program in Java

Graphics Program in Java The graphics program in Java is part of the Swing program in Java. In this section, we will learn about the implementation of custom graphics using some...

6 minutes read.

String Array in Java

String Array in Java An array is alinear data structure that stores similar type of data. It allows us to store fixed number of elements.It can be of different data types...

6 minutes read.

Java AWT

Java AWT Java programming is used to develop different types of applications like window-based applications, web applications, Enterprise applications, or mobile applications. For creating standalone applications, Java AWT API is used....

11 minutes read.

Java.sql.Time Format

In JDBC API as a cover aroundjava.util.Date that handles SQL-specific requirements we use the java.sql.Time. The java.sql.Time extends java.util.Date class. To represent SQL TIME, without a date this class is...

6 minutes read.

Factorial of a Large Number in Java

We've already talked about a number's factorial. We must still go over the factorial of a large number separately, though. The method used to determine the factorial of a small...

8 minutes read.

Types of Bitwise Operators in Java

In this tutorial, we will learn about the various types or kinds of bitwise operators in java. Before proceeding to bitwise operators, let us know what is meant by the...

6 minutes read.

Java Math nextDown() Method

The nextDown() method of Math class returns the floating-point number adjacent to the argument in direction of the negative infinity. Syntax: public static double nextDown (double d)public static float nextDown (float f) Parameters: The...

2 minutes read.

Why are generics used in Java

Java has a feature called generics that allows you to make a class, interface, and function accepting any (reference) type as a parameter. In other words, it is the idea...

4 minutes read.