既存のデータベースにアクセスしてみます。
DBのコネクションをPlayFrameworkから与えることでモデル側でコネクションを作成しません
MySQL
create table OHLC( code varchar(10) not null, date datetime not null, open int null, high int null, low int null, close int null, unique key OHLC1(code,date) )
application.conf
db.default.driver=org.gjt.mm.mysql.Driver db.default.url="jdbc:mysql://localhost/live?useOldAliasMetadataBehavior=true" db.default.user=root db.default.password="" slick.default="models.*" evolutionplugin=disabled
routes
GET /:code controllers.Application.price(code:String)
controllers.Application.scala
package controllers import play.api._ import play.api.mvc._ import play.api.data._ import play.api.data.Forms._ import models._ object Application extends Controller { def price(code:String) = Action{ Ok(views.html.index(Price.select(code))) } }
models.Price.scala
package models import scala.slick.driver.H2Driver.simple._ import Database.threadLocalSession import play.api.db._ import play.api.Play._ import scala.slick.jdbc.{GetResult, StaticQuery => Q} import Q.interpolation case class Price(code:String,date:java.sql.Date,open:Int,high:Int,low:Int,close:Int) object Prices extends Table[Price]("OHLC"){ def scode=column[String]("code",O.PrimaryKey) def date=column[java.sql.Date]("date",O.PrimaryKey) def open=column[Int]("open") def high=column[Int]("high") def low=column[Int]("low") def close=column[Int]("close") def * = code ~ date ~ open ~ high ~ low ~ close <> (Price,Price.unapply _) implicit val getPrice=GetResult(rs=>Price(rs.nextString,rs.nextDate,rs.nextInt,rs.nextInt,rs.nextInt,rs.nextInt)) def price(code:String):List[Price]= connectDB{ sql"select * from OHLC where code=$code".as[Price].list } def connectDB[Any](f: => Any): Any = { Database.forDataSource(DB.getDataSource("default")) withSession { f } } }
views.index.scala.html
@(prices: List[Price]) @prices.map { price => @price.code, @price.date @price.open
}