Govind Singh
Govind Singh

Reputation: 15490

How to execute code when no result selected using Anorm?

This code works fine when there are records matching the WHERE clause:

val pinfo = SQL("SELECT * FROM tableName WHERE id={id}").on("id" -> "scala")
pinfo().map { row =>
  println("have something")// runs when selected
}

What is going to happen when nothing is selected?

I'd like to print the following when no records are selected from MySQL.

println("nothing is selected")//if no row comes

Upvotes: 4

Views: 544

Answers (2)

cchantep
cchantep

Reputation: 9168

You can also parse it as a Option[T], and then handle the case there is no value within this optional result.

val i: Option[Int] = SQL"SELECT int FROM test".as(scalar[String].singleOpt)

Upvotes: 2

Ende Neu
Ende Neu

Reputation: 15783

SQL(...)() returns a Stream[SqlRow] and streams have the isEmpty method:

val pinfo: Stream[SqlRow] = SQL("SELECT * FROM tableName WHERE id={id}").on("id" -> "scala")()
if(!pinfo.isEmpty) pinfo.map { row => println("have something") }
else println("nothing is selected")

Also from the REPL:

scala> 1 #:: 2 #:: empty
res0: scala.collection.immutable.Stream[Int] = Stream(1, ?)

scala> res0.isEmpty
res1: Boolean = false

scala> empty
res2: scala.collection.immutable.Stream[Nothing] = Stream()

scala> res2.isEmpty
res3: Boolean = true

Upvotes: 5

Related Questions