Scala/Slick plain SQL: retrieve result as a map

 ̄綄美尐妖づ 提交于 2019-11-29 15:34:15

问题


I have a simple method to retrieve a user from a db with Sclick plain SQL method:

object Data {

    implicit val getListStringResult = GetResult[List[String]] (
        prs => (1 to prs.numColumns).map(_ => prs.nextString).toList
    )

    def getUser(id: Int): Option[List[String]] = DB.withSession {
        sql"""SELECT * FROM "user" WHERE "id" = $id""".as[List[String]].firstOption
    }

}

The result is List[String] but I would like it to be something like Map[String, String] - column name and value pair map. Is this possible? If so, how?

My stack is Play Framework 2.2.1, Slick 1.0.1, Scala 2.10.3, Java 8 64bit


回答1:


import scala.slick.jdbc.meta._
val columns = MTable.getTables(None, None, None, None)
                    .list.filter(_.name.name == "USER") // <- upper case table name
                    .head.getColumns.list.map(_.column)
val user = sql"""SELECT * FROM "user" WHERE "id" = $id""".as[List[String]].firstOption
                                                         .map( columns zip _ toMap )



回答2:


It's possible to do this without querying the table metadata as follows:

   implicit val resultAsStringMap = GetResult[Map[String,String]] ( prs => 
      (1 to prs.numColumns).map(_ => 
         prs.rs.getMetaData.getColumnName(prs.currentPos+1) -> prs.nextString
      ).toMap
   )

It's also possible to build a Map[String,Any] in the same way but that's obviously more complicated.



来源:https://stackoverflow.com/questions/19891881/scala-slick-plain-sql-retrieve-result-as-a-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!