he SQL statements that read data from a database query return the data in a result set. The SELECT statement is the standard way to select rows from a database and view them in a result set. The java.sql.ResultSet interface represents the result set of a database query.
A ResultSet object maintains a cursor that points to the current row in the result set. The term “result set” refers to the row and column data contained in a ResultSet object.
The methods of the ResultSet interface can be broken down into three categories:
- Navigational methods: used to move the cursor around.
- Get methods: used to view the data in the columns of the current row being pointed to by the cursor.
- Update methods: used to update the data in the columns of the current row. The updates can then be updated in the underlying database as well.
The cursor is movable based on the properties of the ResultSet. These properties are designated when the corresponding Statement that generated the ResultSet is created.
JDBC provides following connection methods to create statements with desired ResultSet:
- createStatement(int RSType, int RSConcurrency);
- prepareStatement(String SQL, int RSType, int RSConcurrency);
- prepareCall(String sql, int RSType, int RSConcurrency);
The first argument indicate the type of a ResultSet object and the second argument is one of two ResultSet constants for specifying whether a result set is read-only or updatable.
Type of ResultSet:
The possible RSType are given below, If you do not specify any ResultSet type, you will automatically get one that is TYPE_FORWARD_ONLY.
|
Type |
Description |
|
ResultSet.TYPE_FORWARD_ONLY |
The cursor can only move forward in the result set. |
|
ResultSet.TYPE_SCROLL_INSENSITIVE |
The cursor can scroll forwards and backwards, and the result set is not sensitive to changes made by others to the database that occur after the result set was created. |
|
ResultSet.TYPE_SCROLL_SENSITIVE. |
The cursor can scroll forwards and backwards, and the result set is sensitive to changes made by others to the database that occur after the result set was created. |
Concurrency of ResultSet:
The possible RSConcurrency are given below, If you do not specify any Concurrency type, you will automatically get one that is CONCUR_READ_ONLY.
|
Concurrency |
Description |
|
ResultSet.CONCUR_READ_ONLY |
Creates a read-only result set. This is the default |
|
ResultSet.CONCUR_UPDATABLE |
Creates an updateable result set. |
Our all the examples written so far can be written as follows which initializes a Statement object to create a forward-only, read only ResultSet object:
|
try { Statement stmt = conn.createStatement( ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); } catch(Exception ex) { …. } |
Navigating a Result Set:
There are several methods in the ResultSet interface that involve moving the cursor, including:
|
S.N. |
Methods & Description |
|
1 |
public void beforeFirst() throws SQLException |
|
2 |
public void afterLast() throws SQLException |
|
3 |
public boolean first() throws SQLException |
|
4 |
public void last() throws SQLException |
|
5 |
public boolean absolute(int row) throws SQLException |
|
6 |
public boolean relative(int row) throws SQLException |
|
7 |
public boolean previous() throws SQLException |
|
8 |
public boolean next() throws SQLException |
|
9 |
public int getRow() throws SQLException |
|
10 |
public void moveToInsertRow() throws SQLException |
|
11 |
public void moveToCurrentRow() throws SQLException |
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
public class TabbedAndDatabaseDemo extends JFrame
{
JTabbedPane tabpane;
TabbedAndDatabaseDemo()
{
tabpane=new JTabbedPane();
getContentPane().add(tabpane);
tabpane.addTab(“Entry of Data”,new EntryData());
pack();
setTitle(” DB”);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300,300);
setVisible(true);
}
public static void main(String[] a)
{
new TabbedAndDatabaseDemo();
}
}
class EntryData extends JPanel implements ActionListener
{
JLabel acc_no,acc_bal,acc_type;
JTextField textno, textbal,texttpe;
JTextArea textarea;
JButton search,button,exit,first,next,last,prev;
ResultSet rs;
Statement st;
Connection cn ;
EntryData()
{
setLayout(new GridLayout(6,1));
acc_no=new JLabel(“No.”);
acc_bal=new JLabel(“Balance”);
acc_type=new JLabel(“Type”);
textno=new JTextField();
textbal=new JTextField();
texttpe=new JTextField();
search = new JButton(“search”);
button = new JButton(“submit”);
exit = new JButton(“exit”);
first= new JButton(“First”);
next= new JButton(“next”);
last= new JButton(“Last”);
prev= new JButton(“Prev”);
button.addActionListener(this);
search.addActionListener(this);
exit.addActionListener(this);
first.addActionListener(this);
next.addActionListener(this);
last.addActionListener(this);
prev.addActionListener(this);
add(acc_no);
add(textno);
add(acc_bal);
add(textbal);
add(acc_type);
add(texttpe);
add(button);
add(exit);
add(first);
add(next);
add(last);
add(prev);
add(search);
try
{
Class.forName(“com.mysql.cj.jdbc.Driver”);
cn=DriverManager.getConnection(“jdbc:mysql://localhost:3306/sydb”,”root”,”pass123″);
st = cn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
rs = st.executeQuery(“SELECT * from account”);
}
catch(Exception ex){System.out.println(ex);}
}
public void actionPerformed(ActionEvent ae)
{
String sql=”SELECT * from account”;
try
{
if(ae.getSource()==button)
{
st = cn.createStatement();
int m = st.executeUpdate(“insert into account values(“+Integer.parseInt(textno.getText())+”,”+textbal.getText()+”,’”+texttpe.getText()+”‘);”);
JOptionPane.showMessageDialog(this,”Record Entered”,”FriendsDatabase”,JOptionPane.ERROR_MESSAGE);
textno.setText(“”);
textbal.setText(“”);
texttpe.setText(“”);
}
else if(ae.getSource()==search)
{
String ser=JOptionPane.showInputDialog(this,”Enter search account”,”Search”,JOptionPane.INFORMATION_MESSAGE);
sql=”SELECT * from account where accno=”+ser;
st = cn.createStatement();
rs = st.executeQuery(sql);
if(rs.next())
{
JOptionPane.showMessageDialog(this,”Found”,”FriendsDatabase”,JOptionPane.ERROR_MESSAGE);
prints(rs);
}
else
JOptionPane.showMessageDialog(this,”not Found”,”FriendsDatabase”,JOptionPane.ERROR_MESSAGE);
}
else if(ae.getSource()==exit)
System.exit(0);
else if(ae.getSource()==first)
{
rs.first();
prints(rs);
}
else if(ae.getSource()==next)
{
rs.next();
}
else if(ae.getSource()==last)
{
rs.last();
prints(rs);
}
else if(ae.getSource()==prev)
{
rs.previous();
prints(rs);
}
}catch(Exception ex){System.out.println(ex);}
}
public void prints(ResultSet rs)
{
textno.setText(rs.getString(“accno”));
textbal.setText(rs.getString(“balance”));
texttpe.setText(rs.getString(“acctype”));
}
}
Viewing a Result Set:
The ResultSet interface contains dozens of methods for getting the data of the current row. There is a get method for each of the possible data types, and each get method has two versions:
- One that takes in a column name.
- One that takes in a column index.
For example, if the column you are interested in viewing contains an int, you need to use one of the getInt() methods of ResultSet:
|
S.N. |
Methods & Description |
|
1 |
public int getInt(String columnName) throws SQLException |
|
2 |
public int getInt(int columnIndex) throws SQLException |
Similarly there are get methods in the ResultSet interface for each of the eight Java primitive types, as well as common types such as java.lang.String, java.lang.Object, and java.net.URL. There are also methods for getting SQL data types java.sql.Date, java.sql.Time, java.sql.TimeStamp, java.sql.Clob, and java.sql.Blob. Check the documentation for more information about using these SQL data types.
import java.sql.*;
public class NavigateExample
{
public static void main(String[] args)
{
Connection conn;
Statement stmt ;
try
{
Class.forName(“com.mysql.cj.jdbc.Driver”);
conn=DriverManager.getConnection(“jdbc:mysql://localhost:3306/sydb”,”root”,”pass123″);
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
String sql=”SELECT * from account”;
ResultSet rs = stmt.executeQuery(sql);
System.out.println(“nMoving cursor to the last…”);
rs.last();
int no = rs.getInt(“accno”);
int bal = rs.getInt(“balance”);
String type = rs.getString(“acctype”);
System.out.print(“No: ” + no);
System.out.print(“, Bal: ” + bal);
System.out.print(“, Type: ” + type);
System.out.println(“nMoving cursor to the first row…”);
rs.first();
no = rs.getInt(“accno”);
bal = rs.getInt(“balance”);
type = rs.getString(“acctype”);
System.out.print(“No: ” + no);
System.out.print(“, Bal: ” + bal);
System.out.print(“, Type: ” + type);
System.out.println(“nMoving cursor to the next row…”);
rs.next();
no = rs.getInt(“accno”);
bal = rs.getInt(“balance”);
type = rs.getString(“acctype”);
System.out.print(“No: ” + no);
System.out.print(“, Bal: ” + bal);
System.out.print(“, Type: ” + type);
rs.close();
stmt.close();
conn.close();
}
catch(SQLException se)
{ se.printStackTrace();}
catch(Exception e)
{ e.printStackTrace();}
}}
Updating a Result Set:
The ResultSet interface contains a collection of update methods for updating the data of a result set. As with the get methods, there are two update methods for each data type:
- One that takes in a column name.
- One that takes in a column index.
For example, to update a String column of the current row of a result set, you would use one of the following updateString() methods:
|
S.N. |
Methods & Description |
|
1 |
public void updateString(int columnIndex, String s) throws SQLException |
|
2 |
public void updateString(String columnName, String s) throws SQLException |
There are update methods for the eight primitive data types, as well as String, Object, URL, and the SQL data types in the java.sql package.
Updating a row in the result set changes the columns of the current row in the ResultSet object, but not in the underlying database. To update your changes to the row in the database, you need to invoke one of the following methods.
|
S.N. |
Methods & Description |
|
1 |
public void updateRow() |
|
2 |
public void deleteRow() |
|
3 |
public void refreshRow() |
|
4 |
public void cancelRowUpdates() |
|
5 |
public void insertRow() |
import java.sql.*;
public class InsertExample
{
public static void main(String[] args)
{
Connection conn;
Statement stmt ;
try
{
Class.forName(“com.mysql.cj.jdbc.Driver”);
conn=DriverManager.getConnection(“jdbc:mysql://localhost:3306/sydb”,”root”,”pass123″);
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql=”SELECT * from account”;
ResultSet rs = stmt.executeQuery(sql);
printRs(rs);
int newBal;
rs.beforeFirst();
while(rs.next())
{
newBal = rs.getInt(“balance”) + 50;
rs.updateInt( “balance”, newBal);
rs.updateRow();
}
System.out.println(“List result set showing new ages…”);
printRs(rs);
System.out.println(“Inserting a new record…”);
rs.moveToInsertRow();
rs.updateInt(“accno”,104);
rs.updateInt(“balance”,4000);
rs.updateString(“acctype”,”saving”);
//Commit row
rs.insertRow();
System.out.println(“List result set showing new set…”);
printRs(rs);
// Set position to second record first
rs.absolute( 2 );
rs.deleteRow();
System.out.println(“List result set after deleting one records…”);
printRs(rs);
rs.close();
stmt.close();
conn.close();
}
catch(SQLException se)
{ se.printStackTrace();}
catch(Exception e)
{ e.printStackTrace();}
}
public static void printRs(ResultSet rs) throws SQLException
{
rs.beforeFirst();
while(rs.next())
{
int no = rs.getInt(“accno”);
int bal = rs.getInt(“balance”);
String type = rs.getString(“acctype”);
System.out.print(“No: ” + no);
System.out.print(“, Bal: ” + bal);
System.out.print(“, Type: ” + type);
System.out.println();
}
}
}