Skip to content

Instantly share code, notes, and snippets.

@aldonline
Created October 13, 2013 07:21
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save aldonline/6959105 to your computer and use it in GitHub Desktop.
Save aldonline/6959105 to your computer and use it in GitHub Desktop.
SQL string to Scala Stream[ResultSet] and common Loan pattern usages when dealing with SQL connections
object x {
// stream a sql query
def sql( str:String ):Stream[ResultSet] = withStatement { s =>
val rs = s executeQuery str
new Iterator[ResultSet] { def hasNext = rs.next ; def next = rs }.toStream
}
// loan a sql statement
def withStatement[R]( f:(Statement) => R ): R =
withConn { c => f( c.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY) ) }
// loan a sql connection
def withConn[R]( f:(java.sql.Connection) => R ):R = {
val conn = DriverManager getConnection "jdbc://..."
try f(conn) finally conn.close()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment