【问题标题】:How to execute code when no result selected using Anorm?使用 Anorm 未选择结果时如何执行代码?
【发布时间】:2014-09-27 15:56:00
【问题描述】:

当有记录匹配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

【问题讨论】:

    标签: mysql scala playframework playframework-2.2 anorm


    【解决方案1】:

    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
    

    【讨论】:

    • 我在使用你的解决方案时遇到了同样的问题,上面写着not found: type SqlRow。你能帮忙
    • 很抱歉,这是很久以前的事了,您确定您的文件中有正确的导入吗?
    • 我已经用你的解决方案导入了anorm._,它可以工作但是现在问题已经解决了,在变量声明中删除了Stream[SqlRow],它就像一个魅力。你的回答真的很有帮助,支持你:)
    【解决方案2】:

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

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

    【讨论】:

    猜你喜欢
    • 2013-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-01
    相关资源
    最近更新 更多