简体   繁体   中英

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

  • housekeeping - how do I close off the resultset and the statement once I am done? I can't think of a way to close the resources in the sql iterator.
  • similarly, in the caller, I would like to wrap the iterator with a try/catch so that on exception, I can close the rs and statement. But I am not sure how to do that? For example, how do I get to the rs and statement to close it??

Thanks in advance for any advice or suggestions.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM