1 import java.sql.SQLException 2 import scala.concurrent.Await 3 import scala.concurrent.duration._ 4 val db = Database.forURL("jdbc:h2:mem:demo", driver="org.h2.Driver") 5 //> db : slick.driver.H2Driver.backend.DatabaseDef = slick.jdbc.JdbcBackend$DatabaseDef@1a5b6f42
6 Await.result( 7 db.run(actions.transactionally).map { res =>
8 println(s"Add coffee: ${res._1},${res._2} and ${res._3},${res._4}") 9 }.recover { 10 case e: SQLException => println("Caught exception: " + e.getMessage) 11 }, Duration.Inf) //> Add coffee: Columbia,128.0 and Blue Mountain,828.0
1 val limit = 10.0
2 sql"select COF_NAME from COFFEES where PRICE < $limit".as[String]
3 // 用$来绑定变量: // select COF_NAME from COFFEES where PRICE < ?
1 package worksheets
2 import slick.driver.H2Driver.api._
3 object slickIntro {
4 case class Coffee(id: Int = 0,
5 name: String,
6 supID: Int = 0,
7 price: Double,
8 sales: Int = 0,
9 total: Int = 0)
10
11 class Coffees(tag: Tag) extends Table[Coffee](tag, "COFFEES") {
12 def id = column[Int]("COF_ID", O.PrimaryKey, O.AutoInc)
13 def name = column[String]("COF_NAME")
14 def supID = column[Int]("SUP_ID")
15 def price = column[Double]("PRICE")
16 def sales = column[Int]("SALES", O.Default(0))
17 def total = column[Int]("TOTAL", O.Default(0))
18 def * = (id, name, supID, price, sales, total) <> (Coffee.tupled, Coffee.unapply)
19 }
20 val coffees = TableQuery[Coffees]
21
22 val limit = 10.0
23 // // 写Query时就像下面这样:
24 ( for( c <- coffees; if c.price < limit ) yield c.name ).result
25 // 相当于 SQL: select COF_NAME from COFFEES where PRICE < 10.0
26
27 // 返回"name"字段的Query
28 // 相当于 SQL: select NAME from COFFEES
29 coffees.map(_.name)
30 // 选择 price < 10.0 的所有记录Query
31 // 相当于 SQL: select * from COFFEES where PRICE < 10.0
32 coffees.filter(_.price < 10.0)
33 //coffees.map(_.prices)
34 //编译错误:value prices is not a member of worksheets.slickIntro.Coffees
35
36
37 import scala.concurrent.ExecutionContext.Implicits.global
38 val qDelete = coffees.filter(_.price > 0.0).delete
39 val qAdd1 = (coffees returning coffees.map(_.id)) += Coffee(name="Columbia",price=128.0)
40 val qAdd2 = (coffees returning coffees.map(_.id)) += Coffee(name="Blue Moun