简体   繁体   中英

Pattern matching using regex with Scala Anorm

I'm Using Scala(2.11) and playframework(2.3) and trying to run a query using a helper function to get results through pattern matching. The function is as follows

def resultsfunc() = {

   val gradeRegex = "^Class 5\."
   val currRegex = "\.NCERT$"

   DB.withConnection{ implicit c =>
     val filterQuery = SQL(
      """
        select * from tbl_graphs
        where graph_name REGEXP '{grade_regex}' and
        graph_name REGEXP '{curr_regex}' and org_id = 4
      """)
      .on("grade_regex" -> gradeRegex,
          "curr_regex" -> currRegex)

    filterQuery().map{ graphRecord =>
        
        new ResultObj(graphRecord[Long]("id"),
                    graphRecord[String]("name"))

       }.toList
    }
}

I don't get any errors but I get empty result even though there are multiple records that match the pattern. The same query works if I try to run in mysql workbench and when I tried to print filterQuery the arguments were also mapped correctly.

Should Pattern matching with regex must be carried out differently in Scala Anorm?

It has absolutely nothing to do specifically with Anorm.

  1. Make sure that executing manually the query with exactly the same data and parameter, you get result.
  2. When using JDBC (even through Anorm), string parameter must not be quoted in the query statement ( ... '{grade_regex}'... ).
  3. Since a long time, it's recommended to use Anorm interpolation ( SQL"SELECT x FROM y WHERE z = ${v}" ) rather than SQL(..) function.

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.

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