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
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With