How to execute code when the result is not selected using Anorm?

This code works great when there are records matching the sentence WHERE:

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

What happens when nothing is selected?

I would like to print the following if no records are selected from MySQL.

println("nothing is selected")//if no row comes
+4
source share
2 answers

SQL(...)()returns a Stream[SqlRow], and threads have a method isEmpty:

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 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
+5
source

You can also analyze it as Option[T], and then handle the case where there is no value in this optional result.

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

All Articles