Arbitrary/Untyped SQL results to a list or seq.

13 views
Skip to first unread message

Rob Canavan

unread,
Aug 16, 2019, 10:55:19 AM8/16/19
to ScalikeJDBC Users Group
Hi, I'm new to scalikejdbc and I'[m trying to figure out how I can run arbitrary SQL statements as strings, then take the results and transform them into a list or seq of Maps.

Something like:

implicit session: DBSession =>
      SQL(s"${query}")
        .map(???)
        .list
        .apply()


I'm using scalikejdbc for a few different purposes, and this particular use case is to run some sql and save the results to an excel file or csv.

Is this something scalike can do easily?

Thanks for any insight.

Rob Canavan

unread,
Aug 16, 2019, 12:32:45 PM8/16/19
to ScalikeJDBC Users Group
Ugh, it was right there in the docs in the nullable Custom Extractor (http://scalikejdbc.org/documentation/2.x/operations.html):

  def toMap(rs: WrappedResultSet): Map[String, Any] =  {
    (1 to rs.metaData.getColumnCount).foldLeft(Map[String, Any]()) { (result, i) =>
      val label = rs.metaData.getColumnLabel(i)
      Some(rs.any(label)).map { nullableValue => result + (label -> nullableValue) }.getOrElse(result)
    }
  }

And just call it like:

 {implicit session: DBSession =>
        SQL(s"${query}").map(a => toMap(a)).list().apply()
      }
Reply all
Reply to author
Forward
0 new messages