implicit conversion of RESULTSET for queries

蓝咒 提交于 2019-12-11 06:57:33

问题


I'm using Scala 2.10 and have problems with Slick (plain queries, java.sql.ResultSet). If I write queries like

Q.query[String, ResultSet](query).list(rs.getString("id"))

eclipse will tell me could not find implicit value for parameter rconv: scala.slick.jdbc.GetResult[java.sql.ResultSet]

My most important source for this issue ( http://slick.typesafe.com/doc/0.11.2/sql.html ) does not help. How do I write these implicit conversions? And is there any other, familar way of representing ResultSets in Slick?


回答1:


Let's me try to shed some light :). Where you have ResultSet, you should have a type you actually map result sets to. E.g. a tuple or a case class that will hold your row. In case of a custom (case) class you will have to provide an implicit GetResult that describes how to map from a jdbc ResultSet to your class. The argument to .list should be a value that you want Slick to put in the placeholder of your prepared statement, not something that you get our of a ResultSet (assuming that that is what rs stands for).

The suggested use is something like this:

import scala.slick.jdbc.{GetResult, StaticQuery}
import StaticQuery.interpolation

val price = 1000.0

// use tuples
val expensiveDevices: List[Device] =
  Q.query[String, (Long,Double,Date)]("select * from DEVICE where PRICE > ?").list( price )

// or a case class (needs implicit GetResult for Device)
case class Device(id: Long,price: Double,acquisition: Date)
implicit val getDeviceResult =
  GetResult(r => Device(r.<<, r.<<, r.<<))
val expensiveDevices2: List[Device] =
  Q.query[String, Device]("select * from DEVICE where PRICE > ?").list( price )

// or the even nicer interpolation syntax
val expensiveDevices3: List[Device] =
  sql"select * from DEVICE where PRICE > $price"    .as[Device].list


来源:https://stackoverflow.com/questions/19243725/implicit-conversion-of-resultset-for-queries

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