Saturday, 21 January 2017

UPDATABLE RESULTSET


  • Default ResultSet is read only. It means data can be read from resultset but cannot do any changes.
  • Resultset mode can be changed to updatable.
  • Updatable resultset allows to do changes within resultset and in database table

How to change ResultSet mode to Updatable

ResultSet mode is changed to updatable at the time of creating Statement or PreparedStatement object. con.prepareStatement(String SQL, int type,int mode)


How to insert row into ResultSet

void moveToInsertRow() - Moves the cursor to the insert row. Insert row is a special row or blank row.

ResultSet provides update methods to replace values. For each data type it provide one update method -
  • updateInt(int columnindex,int value)
  • updateFloat(int columnindex, float value)
  • updateString(int columnindex, String value)
  • updateDouble(int columnindex, Double value)

ResultSet provide the following method to insert into resultset and in database table
  • insertRow();

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Test34 {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:Empdsn","","");
PreparedStatement ps = con.prepareStatement("select * from Emp",ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet rs = ps.executeQuery();
rs.moveToInsertRow();
rs.updateInt(1, 5);
rs.updateString(2, "rockin");
rs.insertRow();
con.close();
}
}


PROGRAM TO DELETE ROW FROM RESULTSET AND DATABASE TABLE

import java.sql.*;
import java.util.Scanner;
public class Test35 {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:Empdsn","","");
PreparedStatement ps = con.prepareStatement("select * from Emp",ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet rs = ps.executeQuery();
Scanner scan = new Scanner(System.in);
System.out.println("input row number");
int row=scan.nextInt();
boolean b =rs.absolute(row);
if(b==false)
{
System.out.println("Invalid row number");
}
else
{
rs.deleteRow();
System.out.println("row deleted from database and resultset");
}
con.close();
}

}



No comments:

Post a Comment