Home Ask Login Register

Developers Planet

Your answer is one click away!

user1591668 February 2016

Slick orm for scala how can I retrieve a database column value

I am new to the Slick ORM using version 3.1.1 and in the examples for plain sql I did not see how I can retrieve the value of a database column http://slick.typesafe.com/doc/3.1.1/sql.html . This is my simple example

 def listfollowing() = Action.async {

   val selectq=sql"""SELECT model,id from carsDB where id=17""".as[(String,Int)]
   // I would like to get the value of model back and put it in a Var
   // var model= model
    database.run(selectq).map {finished=> 

   // I would like to get the value of model back and put it in a Var
   // var model= model


How can I get back the value of the column model so that I could put it in a var or val ?


Liza Shakury February 2016

When you do : database.run(selectq).map {finished=> ... } finished is a Vector[(String,Int)]. If you are sure it returns just one row (because of the "... where id=17") then you can take the headOption() and check if there is a value in it (It would be none if there is no record with id 17) , if there is -> return it else return some error. The code would be something like this:

    def listfollowing() = Action.async {
        val selectq = sql"""SELECT model,id from carsDB where id=17""".as[(String, Int)]
        db.run(selectq).map { finished => 
           finished.headOption match {
              case s: (String, Int) => Ok(s._1)
              case None => Ok("No car found for requested id")

Post Status

Asked in February 2016
Viewed 2,692 times
Voted 7
Answered 1 times


Leave an answer

Quote of the day: live life