I wanted to write a generic solution allowing a user to submit a search criteria and have a servlet return all rows where some field matched the search criteria. I used Java's FilteredResultSet to accomplish this rather than construct a SELECT * FROM table WHERE field1 = criteria OR field2 = criteria, ... and so on and so forth. Here's the bare bones working code.
import java.sql.*;
import java.util.regex.*;
import javax.sql.*;
import javax.sql.rowset.*;
public class CustomFilter {
private static class SearchFilter implements Predicate {
private Pattern pattern; // it's a regular expression
public SearchFilter(String searchRegex){
if ( searchRegex != null && !searchRegex.isEmpty() ){
pattern = Pattern.compile(searchRegex);
}
}
public boolean evaluate(RowSet rset){
boolean result = false;
try{
// test each column to see if it's a match
ResultSetMetaData rsmd = rset.getMetaData();
for ( int index = 1; index <= rsmd.getColumnCount(); index++ ){ // not a zero based array
String columnValue = rset.getString(index);
if ( columnValue != null ){ // it's possible some columns will be null
Matcher matcher = pattern.matcher(columnValue);
if ( matcher.matches() )
return true; // only one column has to match for the row to be included
}
}
}catch(Exception e){
e.printStackTrace(System.err);
};
return false; // no match, no include
}
// don't omit these method stubs
public boolean evaluate(Object value, int column) throws SQLException{
throw new UnsupportedOperationException("implementation pending...");
}
public boolean evaluate(Object value, String columnName) throws SQLException{
throw new UnsupportedOperationException("implementation pending...");
}
}
public static void main(String[] args){
Connection conn = null;
Statement stmt = null;
ResultSet rset = null;
try{
// register the driver
Class.forName("com.mysql.jdbc.Driver");
// get a connection
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mes", "root", "root");
// create a statement
stmt = conn.createStatement();
// get the unfiltered results
String sql = "SELECT * FROM employee";
rset = stmt.executeQuery(sql);
// create a filtered result set
FilteredRowSet frst = RowSetProvider.newFactory().createFilteredRowSet();
// populate it with the unfiltered results
frst.populate(rset);
// create and apply a filter (filters utilise regular expressons)
frst.setFilter(new SearchFilter("^August"));
// dump the results
while ( frst.next() ){
System.out.println(String.format("%s-%s", frst.getString("forename"), frst.getString("surname")));
}
}catch(Exception e){
e.printStackTrace(System.err);
}
}
}
Here's how I compiled and ran it on a Raspberry Pi.
java -cp /usr/share/java/mysql.jar CustomFilter.java
For anyone reading my answer above please note that I added it only for academic completeness in order I might provide a possible solution to the question asked as was (as a Java question).