Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用“on”替换Scala SQL查询中的占位符_Sql_Scala_Playframework 2.0_Anorm - Fatal编程技术网

使用“on”替换Scala SQL查询中的占位符

使用“on”替换Scala SQL查询中的占位符,sql,scala,playframework-2.0,anorm,Sql,Scala,Playframework 2.0,Anorm,我正在尝试创建一个findBy方法,它接受一个键和一个值来搜索一个表。由于某些原因,以下内容未找到任何内容: def findBy(key: String, value: String): Option[Authentication] = DB.withConnection { implicit connection => SQL("select * from authentications where {key}='{value}' limit 1") .on("key" -

我正在尝试创建一个findBy方法,它接受一个键和一个值来搜索一个表。由于某些原因,以下内容未找到任何内容:

def findBy(key: String, value: String): Option[Authentication] = DB.withConnection { implicit connection =>
  SQL("select * from authentications where {key}='{value}' limit 1")
    .on("key" -> key, "value" -> value).as(authentication.singleOpt)
}
但当我只使用加号时,它确实如此。我不介意这样说,但是能够在

def findBy(key: String, value: String): Option[Authentication] = DB.withConnection { implicit connection =>
  SQL("select * from authentications where " + key + "='" + value + "' limit 1")
    .as(authentication.singleOpt)
}

查询示例:
Authentication.findBy(“电子邮件”test@example.com“

Play在准备好的SQL语句中转义查询参数。因此,实际上不需要将
{value}
用单引号括起来。不幸的是,这意味着列名也将通过Play用引号转义,因此数据库将其解释为字符串。如果不使用字符串连接或字符串插值,我看不到解决这个问题的方法

Scala字符串插值会使代码看起来更好一些:

def findBy(key: String, value: String): Option[Authentication] = DB.withConnection { implicit connection =>
    SQL(s"select * from authentications where `$key` = {value} limit 1")
       .as(authentication.singleOpt)
       .on("value" -> value).as(authentication.singleOpt)
}

请注意字符串开头之前的“s”。scala编译器将用范围内的字符串
key
替换标记
$key
。这应该可以工作,但不会转义
。因此,您必须自己清理
键的输入,除非您仅在内部使用它。另外,需要注意的是,
的输入不是表中的一列,它将引发一个
SQLException

这很有趣,但是,反勾号在sql中不起作用,我无法使这个特定的方法起作用。我不知道我做错了什么。反勾号在MySQL中对我有效,但你的结果可能会有所不同。啊,我在使用postgresql,谢谢你,这非常有帮助。