Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 677
Govind Singh Avatar asked Mar 18 '23 20:03

Govind Singh


2 Answers

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
like image 105
Ende Neu Avatar answered Apr 06 '23 07:04

Ende Neu


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)
like image 23
cchantep Avatar answered Apr 06 '23 06:04

cchantep