Groovy GString的问题 [英] Groovy GString issues

查看:132
本文介绍了Groovy GString的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在groovy GString中使用$宏。当我写这段代码的时候




['cdata','tdata']。each {
def sql =select * from $ it_1
}



我得到错误未知属性$ it _



好吧,我正在重写它$ / $>


['cdata', 'tdata']。每个{
def sql =select * from $ {it} _1
}



然后我在结果字符串中获取不需要的引号 - select * from'cdata'_1



问题是我如何使用$ - 宏在GString到达select * from cdata_1结果字符串?

解决方案

您可以使用Groovy的Sql扩展功能来帮助这里。下面的代码可以做到这一点:

  ['cdata','tdata']。each {table  - > def sql =select * from $ {Sql.expand table} _1} 

如果你在GString中有其他参数,这一点尤其重要:

  def name ='Charlie Sheen'
def tables = [ 'normalPeople','crazyPeople']
tables.each {table - >
def sqlString =select * from $ {Sql.expand table} where name = $ {name}
/ *在这里执行SQL * /
}


$ b在上面的例子中,准备好的语句仍然会被使用,'name'变量的内容仍然会作为参数处理从而有助于保护您免受SQL注入攻击),但table variable参数将正确扩展。


I'm want use $ macro in groovy GString. When i'm wrote this code

['cdata','tdata'].each { def sql = "select * from $it_1" }

i'm get error unknown property $it_

ok, i'm rewrite it

['cdata','tdata'].each { def sql = "select * from ${it}_1" }

then i'm get unwanted quotes in result string - "select * from 'cdata'_1"

Question is how i'm can use $-macro in GString to achive "select * from cdata_1" result string?

解决方案

You can use Groovy's Sql expand feature to help here. The following code will do the trick:

['cdata','tdata'].each {table -> def sql = "select * from ${Sql.expand table}_1" }

Using this method is particularly important if you have other parameters in your GString:

def name = 'Charlie Sheen'
def tables = ['normalPeople','crazyPeople']
tables.each { table -> 
    def sqlString = "select * from ${Sql.expand table} where name = ${name}"
    /* Execute SQL here */
}

In the example above a prepared statement will still be used, and the contents of the 'name' variable will still be handled as a parameter (thus helping to protect you against SQL injection attacks) but the table variable parameter will be expanded correctly.

这篇关于Groovy GString的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆