简体   繁体   English

当没有使用Anorm选择结果时如何执行代码?

[英]How to execute code when no result selected using Anorm?

This code works fine when there are records matching the WHERE clause: 当存在与WHERE子句匹配的记录时,此代码可以正常工作:

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. 当没有从MySQL中选择记录时,我想打印以下内容。

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

SQL(...)() returns a Stream[SqlRow] and streams have the isEmpty method: 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")

Also from the REPL: 也来自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

您也可以将其解析为Option[T] ,然后处理此可选结果中没有值的情况。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM