Thursday, September 3, 2009

Scala based automatic resource freeing

Using following scala resource, one freely release resources like(InputStrea, OutputStream, Sockets, JDBC Connection, JDBC ResultSet, JDBC Statements, SSLSocket, ServerSocket)

Source
Example Usage

ResourceTest.scala

object ResourceTest {
import java.sql.{Connection,ResultSet}
val OraPool = ConnPool("orahost152:1521",3, Db ) // some how get oracle jdbc connection

def main ( args : Array[String] ): Unit = {
Resource.use (OraPool.getConnection){ conn =>
val ts = find(conn)
for ( v <- ts ) println(v)
}
}
case class Tab(tname: String, tabtype: String)

def find(conn: Connection): List[Tab] = {
Resource.use(conn.createStatement){st =>
Resource.use (st.executeQuery("select tname,tabtype from tab")){ rs =>
import scala.collection.mutable.ListBuffer
var list = List[Tab]()
while(rs.next()){
list ::= Tab(rs.getString("tname"), rs.getString("tabtype"))
}
list
}
}
}
}

No comments:

Post a Comment