jastrachan | 27 Jul 16:37 2004
Picon

Re: Newbie Groovy syntax questions


On 26 Jul 2004, at 20:45, Pascal DeMilly wrote:

> Hi,
>
> I am a groovy newbie but a veteran programmer. I am trying to 
> understand
> the syntax and have a few questions.
>
> Here is a small script I am trying to run:
>
> s = "select * from Items where Price1 > ${this.args[0]}"
> println "Getting all SKUS for ${s} ..."
>
> crs.eachRow (s) {
>        println "${it.SKU} ${it.Description} ${it.price1}"
> }
>
> When running this script with an argument of 6000 for example, s is
> displayed correctly but the string sent to the SQL server is:
>
> select * from Items where Price1 > ?
>
> Why?

Because we use a JDBC prepared statement. This avoids common SQL 
security issues, like if someone sets s to be something like

s = "'; delete * from some important table;"

:)

> However changing that script like the following, works:
>
> isEligible = { item, price | item.price1 >= price }
>
> crs.eachRow ("select * from Items") {
>     if (isEligible(it, this.args[0])) {
>        println "${it.SKU} ${it.Description} ${it.price1}"
>     }
> }
>
> But is awfully slow.

Well, know you're doing the filter in RAM rather than on the database.

> However I was not able to not use a closure. Why?

Notice that this.args[0] is a String. You might wanna turn that into a 
Number once, outside of a very tight loop.

> crs.eachRow ("select * from Items") {
>    if (${it.price1} > ${this.args[0]}) {
>       println "${it.SKU} ${it.Description} ${it.price1}"
>    }
>
> doesn't work. Why?

You only use the ${} notation inside of a String.

Try

if (it.price1 > someValue) {
     ...
}

James
-------
http://radio.weblogs.com/0112098/


Gmane