A FilteredRowSet object contains only the filtered rows from the database. The filter criteria is set in the RowSet object and the RowSet only get the filtered data from the database to the object. The filters can ebe created by implemeting Predicate interface. The following example will demonstrate the filter object creationg and how to apply the filters in the RowSet object.
package com.visualbuilder;
import java.sql.SQLException;
import javax.sql.RowSet; import javax.sql.rowset.CachedRowSet; import javax.sql.rowset.FilteredRowSet; import javax.sql.rowset.Predicate;
import com.sun.rowset.FilteredRowSetImpl;
class Filter1 implements Predicate { private String colName;
public Filter1(String colName) { this.colName = colName; }
public boolean evaluate(RowSet rs) { try { CachedRowSet crs = (CachedRowSet) rs; String object = crs.getString(colName); if (object != null && (object.charAt(0) == 'A' || object.charAt(0) == 'a')) { return true; } else { return false; } } catch (Exception e) { return false; } }
public boolean evaluate(Object arg0, int arg1) throws SQLException {
return false; }
public boolean evaluate(Object arg0, String arg1) throws SQLException {
return false; } }
public class FillterRowSetExample { public static void main(String[] args) throws Exception { Class.forName("org.postgresql.Driver"); FilteredRowSet frs = new FilteredRowSetImpl(); frs.setUsername("postgres"); frs.setPassword("pass"); frs.setUrl("jdbc:postgresql://localhost:5432/postgres"); frs.setCommand("select id,ename,deptid from employee"); frs.setFilter(new Filter1("ename")); frs.execute(); while (frs.next()) { System.out.println("Employee is " + frs.getString("id")); System.out.println("Department is " + frs.getString("ename")); } } }
Output:-
Employee is Adam
Department is Sales
Employee is Adran
Department is Marketing
|