如何在Slick 3.x中获取?

时间:2015-12-11 22:37:05

标签: playframework slick

我有以下代码,它将OK连接到数据库,但是我不知道如何打印每一行(相当于JDBC中的rs.next):

val db = Database.forConfig("dbconfig")
try {
    val users: TableQuery[Users] = TableQuery[Users]
    // fetch each user and print it
    println("user : " + ??? )

} finally db.close

任何帮助将不胜感激,为新手问题道歉。

3 个答案:

答案 0 :(得分:1)

请检查documentation。我也是斯卡拉和浮油的新手。希望这会对你有所帮助。

val db = Database.forConfig("dbconfig")
try {
    val users: TableQuery[Users] = TableQuery[Users]

    // fetch each user and print it
    // You need to import database driver...
    // import slick.driver.MySQLDriver.api._

    val usersListQueryResult = db.run(users.result) //it returns, Future[R]

    // Now you can use blocking or non blocking call
    val userList = Await.result(usersListQueryResult, Duration("60 seconds")) //Blocking
    // OR 
    usersListQueryResult.foreach(println) //NonBlocking
} finally db.close

答案 1 :(得分:1)

您也可以尝试以下

val db = Database.forConfig("dbconfig")
try {
    val users: TableQuery[Users] = TableQuery[Users]

    val printingAction:DBIO[Unit] =
      for{seqUsers <- users.result}  // DBIO[Seq[User]]
        for{ user <- seqUsers}       // simple executable code, :Unit 
          println("user : " + user )

    val future = db.run(printingAction)
    Await.result(future, 60.seconds) // need to wait before close db    
} finally db.close

(这与@ Shakil的答案非常相似)

答案 2 :(得分:1)

Slick还有另一个选项:http://slick.typesafe.com/doc/3.1.0/dbio.html#streaming

val db = Database.forConfig("dbconfig")
try {
    val users: TableQuery[Users] = TableQuery[Users]    
    val p: DatabasePublisher[User] = db.stream(users.result)
    p.foreach { user  => println("user : " + user ) }
} finally db.close