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

问题描述

我想在 groovy GString 中使用 $ 宏.当我写下这段代码

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

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

我收到错误未知属性 $it_

i'm get error unknown property $it_

好的,我改写了

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

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

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

问题是我如何在 GString 中使用 $-macro 来实现select * from cdata_1"结果字符串?

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

推荐答案

您可以使用 Groovy 的 Sql 扩展功能来帮助这里.以下代码可以解决问题:

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" }

如果您的 GString 中有其他参数,则使用此方法尤为重要:

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 */
}

在上面的示例中,仍将使用准备好的语句,并且 'name' 变量的内容仍将作为参数处理(从而有助于保护您免受 SQL 注入攻击),但表变量参数将被扩展正确.

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 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 14:40