Eddard Stark
Eddard Stark

Reputation: 3595

Query using date in grails

I am trying to run a query in grails and one of the fields i want to filter from is a datetime type in mysql. I tried doing this:

def formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
def timeNow = formatter.format(new Date())
foundUsers = User.executeQuery("from User u where u.username LIKE '%"+params.searchStr+"%' and u.enabled =1 and u.expiration_date>"+timeNow,[max:20])

but this is giving me an error: unexpected token ! I cannot change the domain User and the database because they are old and contain live data. So how do i do this ?

Upvotes: 0

Views: 2577

Answers (2)

Aram Arabyan
Aram Arabyan

Reputation: 2359

  1. I belie unexpected token is because of '>' after u.expiration_date
  2. Your code is not save for sql injection.
  3. Your cod should be something like this

    def foundUsers= User.findByUsernameLikeAndEnabledAndExpiration_date('%params.searchStr%',1,timeNow)

Read more about Dynamic Finders

http://grails.org/doc/latest/guide/GORM.html#querying

Upvotes: 2

Kelly
Kelly

Reputation: 3709

Try this:

    foundUsers = User.executeQuery("from User u where u.username LIKE ? and u.enabled = 1 and u.expiration_date > ?",['%params.searchStr%', timeNow],[max:20])

Upvotes: 0

Related Questions