简体   繁体   English

如何在Anorm查询中使用'like'?

[英]How to use 'like' in Anorm query?

My Data base is porstgres, and I am trying to write a query that will use like or ~ (postgres regex). 我的数据库是porstgres,我正在尝试编写一个使用like或〜(postgres regex)的查询。 I couldn't write this query using on. 我无法使用on编写此查询。

so here is what I tried to write: 所以这就是我试着写的:

SQL(s"""SELECT id, name
       |FROM my_table 
       |WHERE name ~ '^{name}'""")
.on('name -> name).as(parser.*)

Or: 要么:

SQL(s"""SELECT id, name
       |FROM my_table 
       |WHERE name like '{name}%'""")
.on('name -> name).as(parser.*)

The code that is working for me does not use on. 适合我的代码不使用。 And it looks like this: 它看起来像这样:

SQL(s"""SELECT id, name
       |FROM my_table 
       |WHERE name """.concat(s"like '$name%'").as(parser.*)

Is there a better way to achieve this? 有没有更好的方法来实现这一目标?

When having a ... '{param}' with a string value passed using .on , the JDBC statement is prepared as ... ''$strVal'' , as the value is escaped according JDBC. 当使用.on使用.on传递的字符串值的... '{param}'时,JDBC语句准备为... ''$strVal'' ,因为该值是根据JDBC转义的。

So the the single quotes should be removed from the SQL statement, and the % , must be part of the escaped string value. 因此,应从SQL语句中删除单引号, %必须是转义字符串值的一部分。

SQL("""SELECT id, name
   |FROM my_table 
   |WHERE name like {name}""")
  .on('name -> s"{name}%").as(parser.*)

Moreover, there the String Interpolation is useless ( SQL(s"...") should be SQL("...") ), as Anorm placeholder are not prepared using that. 此外,String Interpolation是无用的( SQL(s"...")应该是SQL("...") ),因为Anorm占位符不是使用它准备的。

If you want to use interpolation, it would be better to use Anorm one. 如果你想使用插值,最好使用Anorm one。

SQL"""SELECT id, name
   |FROM my_table 
   |WHERE name like ${name + "%"}""".
  as(parser.*)

I believe the problem is that you're trying to pass a parameter to inside of a string. 我相信问题是你试图将参数传递给字符串内部。

What I mean is that instead of WHERE name like '{name}%' it should be just WHERE name like {name} . 我的意思是,而不是WHERE name like '{name}%'WHERE name like '{name}%'它应该只是WHERE name like {name}

SQL(s"""SELECT id, name
       |FROM my_table 
       |WHERE name like {name}""")
.on('name -> "foo%").as(parser.*)

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

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