My Data base is porstgres, and I am trying to write a query that will use like or ~ (postgres regex). I couldn't write this query using 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.
So the the single quotes should be removed from the SQL statement, and the %
, must be part of the escaped string value.
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.
If you want to use interpolation, it would be better to use 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}
.
SQL(s"""SELECT id, name
|FROM my_table
|WHERE name like {name}""")
.on('name -> "foo%").as(parser.*)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.