×

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

Int vs Integer in Java

In Java, numerical data can be stored using int or Integer. int and Integer both have different definitions but similar usage in Java. What is int in Java? int is a primitive...

4 minutes read.

Display Unique Rows in a Binary Matrix in Java

To solve this problem, we must first locate and display the distinct rows of a supplied binary matrix afterward. We will go through how to show distinct rows inside a...

12 minutes read.

Difference between = = and equals ( ) in java

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

6 minutes read.

Java Long Keyword

Long is a primitive data type in Java. To initilize variables, we implement the long keyword. It can also be applied to techniques. A 64-bit two's complement integer can put...

3 minutes read.

Java inheritance with Example

Java inheritance Java inheritance is a mechanism in which a child object acquires all the properties and behaviors of a parent object. It helps in reusing the code and establishes...

7 minutes read.

Java Default Keyword

The Default keyword in java programming language is used as access modifier.If any of the variable or the constructor or the methods or the classes are not assigned with the...

3 minutes read.

Permutation Coefficient in Java

In this tutorial, we will get familiar with the permutation coefficient in Java.  We will understand it through examples and see different approaches to solving the problem. A permutation is a...

5 minutes read.

Misc Operators in Java

In this article, we are going to learn about the misc operators in Java. Misc operators are nothing but the miscellaneous operators. The java programming language supports some of the...

4 minutes read.

Java IO file not found exception

One of the exception classes offered by the java.io package is FileNotFoundException. An exception is raised when we attempt to access a file that isn't present in the system. It...

4 minutes read.

Java Integer class

The Integer class wraps a primitive int type value in an object. Its object contains only a single field whose type is int. Methods: The java.lang.Integer class provides several different methods for...

4 minutes read.

Encapsulation Program in Java

Encapsulation Program in Java Encapsulation program in Java demonstrates the technique to bind methods and fields in a single unit. The term encapsulation is inspired by the word ‘capsule’, which is...

3 minutes read.

Java Thread Lifecycle: States and Stages

Multithreading Multithreading is one of the most important features in object-oriented programming, and this multithreading can be implemented by various object-oriented programming languages like Java, Python, and C++. A multithreaded process...

7 minutes read.

Java Public Keyword

A Java access modifier is a public keyword. It can be applied to classes, constructors, methods, and variables. It is the type of access modifier that is least constrained. A...

4 minutes read.

Chromatic Number in Java

The chromatic number is the bare minimum of colours necessary to accurately colour any graph. To put it another way, the chromatic number can be thought of as the bare...

6 minutes read.

Java Date add Days

In order to operate with the time and the Date in Java, we used the abstract Calendar class. It has several helpful interfaces that enable us to convert dates between...

4 minutes read.

How to Convert String to double in Java

How to Convert String to double in java It is used if we have to perform mathematical operations on the string that contains a double number. When we get data from...

3 minutes read.

Exception Handling Program in Java

Exception Handling Program in Java Exception means something that is abnormal. In Java, an exception is treated as a problem that disrupts the normal flow of the program. An exception leads...

7 minutes read.

Java delete directory

The File classes in Java may symbolize a directory or a file on the system. Inside the java.io package, the Files class is accessible. The File class has several helpful...

2 minutes read.

Abstract classes in Java

Abstract classes in Java Java uses the 'abstract’ keyword to make a class abstract. Such classes are known as abstract classes, and the process is known as abstraction. In programming language, abstract...

4 minutes read.

Java Integer getInteger() method

The getInteger() method of Integer class determines the integer value of the system property with the given name. Syntax` public static Integer getInteger(String nm) Parameters The parameter ‘nm’ represents the property name. Throws The getInteger ()...

1 minute read.