Bernie Wong
Bernie Wong

Reputation: 701

How to handle exceptions in a JDBC ResultSet Iterator

I have a couple of housekeeping and exception handling questions around processing JDBC ResultSets as Iterators (see code below -- specifically the sql function).

class SqlHelper(prop: Properties) {

  val conn = {
    Class.forName(prop.getProperty("drivername"))
    DriverManager.getConnection(prop.getProperty("jdbcurl"), prop.getProperty("username"), prop.getProperty("password"))
  }

  def sql(conn: Connection, s: String): Iterator[ResultSet] = {
    val rs = conn.createStatement.executeQuery(s)
    Iterator.
      continually(rs.next, rs).
      takeWhile(_._1).
      map(_._2)
  }
}

The caller would find work (to do) and pass it to an Akka worker actor. Once it is done, it will repeat that loop.

  def doWork = {
    val sqlhelper = new SqlHelper(new Properties())

    while (true) {
      try {
        sqlhelper.
          sql("select work_key from wip_table where need_to_process = 'Y'").
          foreach(k => worker ! Work(k.getString("work_key")))
        ?????? how to clean up after finishing ????
      } catch {
        case e: Exception =>
          e.printStackTrace()
          ?????? how to clean up after exception ????
      }
    }
  }

My questions are

Thanks in advance for any advice or suggestions.

Upvotes: 1

Views: 125

Answers (1)

Mario Galic
Mario Galic

Reputation: 48430

Try scala.util.Using perhaps like so

Using.resource(DriverManager.getConnection(...)) { conn =>
  val rs = conn.createStatement.executeQuery(s)
  Iterator
    .continually(rs.next, rs)
    .takeWhile(_._1)
    .map(_._2)
    .foreach(...)
}

According to Using.resource docs :

Performs an operation using a resource, and then releases the resource, even if the operation throws an exception. This method behaves similarly to Java's try-with-resources.

Upvotes: 1

Related Questions