簡體   English   中英

當沒有使用Anorm選擇結果時如何執行代碼?

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

當存在與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

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

您也可以將其解析為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