当存在与WHERE
子句匹配的记录时,此代码可以正常工作:
val pinfo = SQL("SELECT * FROM tableName WHERE id={id}").on("id" -> "scala")
pinfo().map { row =>
println("have something")// runs when selected
}
什么都没有被选中会发生什么?
如果没有从MySQL中选择任何记录,我想打印以下内容。
println("nothing is selected")//if no row comes
答案 0 :(得分:5)
SQL(...)()
会返回Stream[SqlRow]
,并且流会使用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")
同样来自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
答案 1 :(得分:2)
您也可以将其解析为Option[T]
,然后处理此可选结果中没有值的情况。
val i: Option[Int] = SQL"SELECT int FROM test".as(scalar[String].singleOpt)