tags:

views:

226

answers:

2

Does anyone know good source where I can find about implementation of SQL iterator/Operator in java and any other languages? Than you, -Nimesh

A: 

How about look at some source code of either JDK or open source jdbc drivers such as mysql's?

Journeyman Programmer
+1  A: 

I'm going to go with Elijah's interpretation, that Nimesh actually meant, "Is it possible to make a wrapper Iterable for a ResultSet. Here's something I whipped up. It's obviously not yet production-ready, but it definitely gives the idea. Since there is no standard (as far as I know) ResultSetRow, it returns an Object[] for each row.

There are some significant issues with this concept, not least that Iterator is not allowed to throw, so SQLExceptions are handled as best possible "on-site". Also, ResultSet is a very complex and featureful beast (see for instance the overloaded methods for every type). This complexity could be partially taken advantage of but isn't. For instance, there could be methods like getIntIterable(ResultSet rs) which returns a Iterable<int[]>. The method could check the getColumnTypes of the ResultSetMetadata object. That way, it could throw (if for instance not all columns are ints) before creating the Iterable, the methods of which can not throw.

public static class ResultSetIterable implements Iterable<Object[]>
{
private ResultSet rs;
private int columnCount;

public ResultSetIterable(ResultSet rs) throws SQLException
{
    this.rs = rs;
    columnCount = rs.getMetaData().getColumnCount();
}

public Iterator<Object[]> iterator()
{
    return new Iterator<Object[]>() 
    {
 private boolean moreRows;
 {
     try
     {
  moreRows = rs.first();
     }
     catch(SQLException e)
     {
  moreRows = false;
     }
 }

 public boolean hasNext()
 {
     boolean knownClosed = false;
     try
     {
  knownClosed = rs.isClosed();
     }
     catch(Throwable e)
     {
  // Ignore possible SQLException or AbstractMethodError or...
     }

     return !knownClosed && moreRows;
 }

 public Object[] next()
 {
     Object[] curRow = new Object[columnCount];
     for(int i = 1; i <= columnCount; i++)
     {
  try
  {
      curRow[i - 1] = rs.getObject(i);
  }
  catch(SQLException e)
  {
      curRow[i - 1] = null;
  }
     }
     try
     {
  moreRows = rs.next();
     }
     catch(SQLException e)
     {
  moreRows = false;
     }
     return curRow;
 }

 public void remove()
 {
     try
     {
  rs.previous();
  rs.deleteRow();
     }
     catch(SQLException e)
     {
  throw new UnsupportedOperationException("ResultSetIterable does not support remove for this ResultSet type.");
     }
 }
    };
}
}
Matthew Flaschen